/** 题目:poj3680 Intervals 区间k覆盖问题 最小费用最大流 建图巧妙 链接:http://poj.org/problem?id=3680 题意:给定n个区间,每个区间(ai,bi),以及权值wi。选出一些区间,满足权值和最大且任何一个点不会被超过k个区间覆盖。 思路: 建图:对于每个区间(ai,bi)。 ai->bi,cap = 1,cost = -wi; (离散化后的ai,bi) 所有区间的端点放到数组,进行从小到大排序,去重,离散化,在数组内相邻的u端点,v端点。u->v,cap = INF,cost=0; s->x最左边的那个端点(也就是离散化后最小的那个数),cap = k, cost = 0; x(最右边的那个端点)->t,cap = k, cost = 0; 求s->t的最小费用最大流,输出-cost即为结果。 可以把图想象成一个x轴上有若干端点,(ai,bi)上面连了一条弧线。从最左边开始跑,到最右边,如果最左边cap=k。 那么最多k流量往右边流,每个点最多被k流量覆盖,每一个单位流量分配给一个区间(ai,bi),所以最多被k个区间覆盖。 */ #include<iostream> #include<cstring> #include<vector> #include<map> #include<cstdio> #include<sstream> #include<algorithm> #include<queue> using namespace std; typedef long long LL; const int INF = 0x3f3f3f3f; const int N = 420; struct Edge{ int from, to, cap, flow, cost; Edge(int u,int v,int c,int f,int w):from(u),to(v),cap(c),flow(f),cost(w){} }; struct MCMF{ int n, m; vector<Edge> edges; vector<int> G[N]; int inq[N]; int d[N]; int p[N]; int a[N]; void init(int n){ this->n = n; for(int i = 0; i <= n; i++) G[i].clear(); edges.clear(); } void AddEdge(int from,int to,int cap,long long cost){ edges.push_back(Edge(from,to,cap,0,cost)); edges.push_back(Edge(to,from,0,0,-cost)); m = edges.size(); G[from].push_back(m-2); G[to].push_back(m-1); } bool BellmanFord(int s,int t,int &flow,long long &cost){ for(int i = 0; i <= n; i++) d[i] = INF; memset(inq, 0, sizeof inq); d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF; queue<int> Q; Q.push(s); while(!Q.empty()){ int u = Q.front(); Q.pop(); inq[u] = 0; for(int i = 0; i < G[u].size(); i++){ Edge& e = edges[G[u][i]]; if(e.cap>e.flow&&d[e.to]>d[u]+e.cost){ d[e.to] = d[u]+e.cost; p[e.to] = G[u][i]; a[e.to] = min(a[u],e.cap-e.flow); if(!inq[e.to]) {Q.push(e.to); inq[e.to] = 1;} } } } if(d[t]==INF) return false; flow += a[t]; cost += (long long)d[t]*(long long)a[t]; for(int u = t; u!=s; u = edges[p[u]].from){ edges[p[u]].flow+=a[t]; edges[p[u]^1].flow-=a[t]; } return true; } int MincostMaxflow(int s,int t,long long &cost){ int flow = 0; cost = 0; while(BellmanFord(s,t,flow,cost)); return flow; } }; int u[N], v[N], w[N]; vector<int> vv; map<int,int> mp; int main() { int T, n, k; cin>>T; while(T--) { int s = 0, t; scanf("%d%d",&n,&k); vv.clear(); for(int i = 1; i <= n; i++){ scanf("%d%d%d",&u[i],&v[i],&w[i]); vv.push_back(u[i]); vv.push_back(v[i]); } sort(vv.begin(),vv.end()); vv.erase(unique(vv.begin(),vv.end()),vv.end());///相邻重复元素,多余出来的全部放到后面,并返回一个开始指针 mp.clear(); for(int i = 0; i < vv.size(); i++){ mp[vv[i]] = i+1; } t = vv.size()+1; MCMF mcmf; mcmf.init(t); mcmf.AddEdge(s,1,k,0); mcmf.AddEdge(vv.size(),t,k,0); for(int i = 1; i < vv.size(); i++){ mcmf.AddEdge(i,i+1,INF,0); } for(int i = 1; i <= n; i++){ mcmf.AddEdge(mp[u[i]],mp[v[i]],1,-w[i]); } LL cost; int flow = mcmf.MincostMaxflow(s,t,cost); printf("%lld ",-cost); } return 0; }