首页 > 代码库 > POJ 3680 Intervals
POJ 3680 Intervals
离散化+最大费用最大流...
源点---1 .. 2 ..3 .... n ---汇点 连流量为K,费用为0的边
对于(a , b , w) 连从 a到b容量1费用w的边
Intervals
Description You are given N weighted open intervals. The ith interval covers (ai, bi) and weighs wi. Your task is to pick some of the intervals to maximize the total weights under the limit that no point in the real axis is covered more than k times. Input The first line of input is the number of test case. Output For each test case output the maximum total weights in a separate line. Sample Input 4 3 1 1 2 2 2 3 4 3 4 8 3 1 1 3 2 2 3 4 3 4 8 3 1 1 100000 100000 1 2 3 100 200 300 3 2 1 100000 100000 1 150 301 100 200 300 Sample Output 14 12 100000 100301 Source POJ Founder Monthly Contest – 2008.07.27, windy7926778 |
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> #include <vector> using namespace std; const int maxn=500; const int INF=0x3f3f3f3f; struct Edge { int to,next,cap,cost,flow; }edge[maxn*maxn]; int Adj[maxn],Size,N; void init() { Size=0; memset(Adj,-1,sizeof(Adj)); } void addedge(int u,int v,int cap,int cost) { edge[Size].to=v; edge[Size].next=Adj[u]; edge[Size].cost=cost; edge[Size].cap=cap; edge[Size].flow=0; Adj[u]=Size++; } void Add_Edge(int u,int v,int cap,int cost) { addedge(u,v,cap,cost); addedge(v,u,0,-cost); } int dist[maxn],vis[maxn],pre[maxn]; bool spfa(int s,int t) { queue<int> q; for(int i=0;i<N;i++) { dist[i]=-INF; vis[i]=false; pre[i]=-1; } dist[s]=0; vis[s]=true; q.push(s); while(!q.empty()) { int u=q.front(); q.pop(); vis[u]=false; for(int i=Adj[u];~i;i=edge[i].next) { int v=edge[i].to; if(edge[i].cap>edge[i].flow&& dist[v]<dist[u]+edge[i].cost) { dist[v]=dist[u]+edge[i].cost; pre[v]=i; if(!vis[v]) { vis[v]=true; q.push(v); } } } } if(pre[t]==-1) return false; return true; } int MinCostMaxFlow(int s,int t,int& cost) { int flow=0; cost=0; while(spfa(s,t)) { int Min=INF; for(int i=pre[t];~i;i=pre[edge[i^1].to]) { if(Min>edge[i].cap-edge[i].flow) Min=edge[i].cap-edge[i].flow; } for(int i=pre[t];~i;i=pre[edge[i^1].to]) { edge[i].flow+=Min; edge[i^1].flow-=Min; cost+=Min*edge[i].cost; } flow+=Min; } return flow; } int n,m,K; struct Bian { int u,v,w; }bian[maxn]; int has[maxn],hn; int main() { int T_T; scanf("%d",&T_T); while(T_T--) { init();hn=0; scanf("%d%d",&m,&K); for(int i=0;i<m;i++) { int a,b,c; scanf("%d%d%d",&a,&b,&c); bian[i].u=a; bian[i].v=b; bian[i].w=c; has[hn++]=a; has[hn++]=b; } sort(has,has+hn); hn=unique(has,has+hn)-has; n=hn+2; N=n; for(int i=1;i<n;i++) { Add_Edge(i-1,i,K,0); } for(int i=0;i<m;i++) { bian[i].u=lower_bound(has,has+hn,bian[i].u)-has+1; bian[i].v=lower_bound(has,has+hn,bian[i].v)-has+1; Add_Edge(bian[i].u,bian[i].v,1,bian[i].w); } int flow,cost; flow=MinCostMaxFlow(0,n-1,cost); printf("%d\n",cost); } return 0; }
POJ 3680 Intervals