标签:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 64044 | Accepted: 24718 |
Description
Input
Output
Sample Input
5 4 1 2 40 1 4 20 2 4 20 2 3 30 3 4 10
Sample Output
50
代码:醉醉的超时。。。入门题。两种方法:
代码1:
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<cmath> 5 #include<queue> 6 #include<algorithm> 7 #define mem(x,y) memset(x,y,sizeof(x)) 8 #include<queue> 9 using namespace std; 10 typedef long long LL; 11 const int INF=0x3f3f3f3f; 12 const int MAXN=210; 13 int map[MAXN][MAXN]; 14 queue<int>dl; 15 int vis[MAXN],pre[MAXN]; 16 int N; 17 bool bfs(int s,int e){ 18 mem(vis,0); 19 mem(pre,0); 20 while(!dl.empty())dl.pop(); 21 vis[s]=1;dl.push(s); 22 int a; 23 while(!dl.empty()){ 24 a=dl.front();dl.pop(); 25 if(a==e)return true; 26 for(int i=1;i<=N;i++){ 27 if(!vis[i]&&map[a][i]){ 28 vis[i]=1; 29 dl.push(i); 30 pre[i]=a; 31 } 32 } 33 } 34 return false; 35 } 36 LL maxflow(int s,int e){ 37 LL flow=0; 38 while(bfs(s,e)){ 39 int r=e; 40 int temp=INF; 41 while(r!=s){ 42 temp=min(temp,map[pre[r]][r]); 43 r=pre[r]; 44 } 45 r=e; 46 while(r!=s){ 47 map[pre[r]][r]-=temp; 48 map[r][pre[r]]+=temp; 49 r=pre[r];//这句话不能少。。 50 } 51 flow+=temp; 52 } 53 return flow; 54 } 55 int main(){ 56 int M; 57 while(~scanf("%d%d",&M,&N)){ 58 mem(map,0); 59 int u,v,w; 60 while(M--){ 61 scanf("%d%d%d",&u,&v,&w); 62 map[u][v]+=w; 63 } 64 printf("%I64d\n",maxflow(1,N)); 65 } 66 return 0; 67 }
代码2:
#include<cstdio> #include<iostream> #include<cstring> #include<cmath> #include<queue> #include<algorithm> #define mem(x,y) memset(x,y,sizeof(x)) using namespace std; const int INF=0x3f3f3f3f; typedef long long LL; const int MAXN=210; const int MAXM=2020; int head[MAXM]; int vis[MAXN],dis[MAXN]; int edgnum; struct Node{ int from,to,next,cup,flow; }; Node edg[MAXM]; queue<int>dl; void initial(){ mem(head,-1);edgnum=0; } void add(int u,int v,int w){ Node E={u,v,head[u],w,0}; edg[edgnum]=E; head[u]=edgnum++; E={v,u,head[v],0,0}; edg[edgnum]=E; head[v]=edgnum++; } bool bfs(int s,int e){ mem(vis,0);mem(dis,-1); while(!dl.empty())dl.pop(); vis[s]=1;dis[s]=0;dl.push(s); while(!dl.empty()){ int u=dl.front();dl.pop(); for(int i=head[u];i!=-1;i=edg[i].next){ Node v=edg[i]; if(!vis[v.to]&&v.cup>v.flow){//应该是> vis[v.to]=1; dis[v.to]=dis[u]+1; if(v.to==e)return true; dl.push(v.to); } } } return false; } int dfs(int x,int la,int e){ if(x==e||la==0)return la; int temp; LL flow=0; for(int i=head[x];i!=-1;i=edg[i].next){ Node &v=edg[i]; if(dis[v.to]==dis[x]+1&&(temp=dfs(v.to,min(la,v.cup-v.flow),e))>0){//这里也应该要> v.flow+=temp; edg[i^1].flow-=temp; la-=temp; flow+=temp; if(la==0)break;//这个要判断 } } return flow; } LL maxflow(int s,int e){ LL flow=0; while(bfs(s,e)){ flow+=dfs(s,INF,e); } return flow; } int main(){ int N,M; while(~scanf("%d%d",&N,&M)){ initial(); int u,v,w; while(N--){ scanf("%d%d%d",&u,&v,&w); add(u,v,w); } printf("%I64d\n",maxflow(1,M)); } return 0; }
标签:
原文地址:http://www.cnblogs.com/handsomecui/p/4936970.html