标签:
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 14059 | Accepted: 5354 |
Description
Input
Output
Sample Input
4 5
1 2 1
2 3 1
3 4 1
1 3 2
2 4 2
Sample Output
6
题解:
最小费用最大流模板直接上,注意是双向边。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstdlib> 4 #include<cmath> 5 #include<algorithm> 6 #include<cstring> 7 #include<queue> 8 #include<vector> 9 using namespace std; 10 const int inf=1e9; 11 const int maxn=2000,maxm=3000000; 12 struct node{ 13 int to,rest,next,cost; 14 }e[maxm]; 15 int head[maxn],cnt=1; 16 inline void addedge(int x,int y,int z,int c){ 17 e[++cnt].to=y; e[cnt].rest=z; e[cnt].next=head[x]; head[x]=cnt; e[cnt].cost= c; 18 e[++cnt].to=x; e[cnt].rest=0; e[cnt].next=head[y]; head[y]=cnt; e[cnt].cost=-c; 19 } 20 int N,M,S,T; 21 int dis[maxn],pre[maxn]; 22 bool vis[maxn]; 23 int maxflow,mincost; 24 bool SPFA(){ 25 static queue<int> Q; 26 for(int i=S;i<=T;i++) dis[i]=inf,vis[i]=false; 27 Q.push(S); dis[S]=0; vis[S]=true; 28 while(!Q.empty()){ 29 int x=Q.front(); Q.pop(); 30 vis[x]=false; 31 for(int i=head[x];i;i=e[i].next){ 32 int y=e[i].to; 33 if(e[i].rest&&dis[y]>dis[x]+e[i].cost){ 34 dis[y]=dis[x]+e[i].cost; 35 pre[y]=i; 36 if(vis[y]==false){ 37 vis[y]=true; 38 Q.push(y); 39 } 40 } 41 } 42 } 43 return dis[T]<inf; 44 } 45 void update(){ 46 int flow=inf; 47 for(int i=pre[T];i;i=pre[e[i^1].to]) 48 flow=min(flow,e[i].rest); 49 for(int i=pre[T];i;i=pre[e[i^1].to]){ 50 e[i].rest-=flow; 51 e[i^1].rest+=flow; 52 } 53 maxflow+=flow; mincost+=flow*dis[T]; 54 } 55 void MCF(){ 56 maxflow=mincost=0; 57 while(SPFA()) update(); 58 } 59 int main(){ 60 scanf("%d%d",&N,&M); 61 S=0; T=N+1; 62 addedge(S,1,2,0); 63 for(int i=1,u,v,c;i<=M;i++){ 64 scanf("%d%d%d",&u,&v,&c); 65 addedge(u,v,1,c); 66 addedge(v,u,1,c); 67 } 68 addedge(N,T,2,0); 69 MCF(); 70 printf("%d",mincost); 71 return 0; 72 }
标签:
原文地址:http://www.cnblogs.com/CXCXCXC/p/5207954.html