标签:des style blog http color io os java ar
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9580 Accepted Submission(s): 4541
1 #include<cstdio> 2 #include<cstring> 3 #include<queue> 4 #include<iostream> 5 #include<algorithm> 6 using namespace std; 7 const int inf=0x3f3f3f3f; 8 const int maxn=501; 9 int map[maxn][maxn]; 10 int dist[maxn]; 11 int n,m; 12 int bfs(int st,int en){ 13 int t; 14 queue<int>q; 15 memset(dist,-1,sizeof(int)*(m+1)); 16 q.push(st); 17 dist[st]=0; 18 while(!q.empty()){ 19 t=q.front(); 20 q.pop(); 21 for(int i=1;i<=m;i++){ 22 if(map[t][i]>0&&dist[i]<0){ 23 dist[i]=dist[t]+1; 24 q.push(i); 25 } 26 } 27 } 28 if(dist[en]>0) return 1; 29 return 0; 30 } 31 int dfs(int st,int en,int flow){ 32 int tem=0; 33 if(st==en||flow==0)return flow; 34 for(int i=1;i<=m;i++) 35 { 36 if(dist[i]==dist[st]+1&&map[st][i]>0&&(tem=dfs(i,en,min(map[st][i],flow)))) 37 { 38 map[st][i]-=tem; 39 map[i][st]+=tem; 40 return tem; 41 } 42 } 43 return 0; 44 } 45 void Dinic(int st,int en) 46 { 47 int ans=0; 48 while(bfs(st,en)) 49 ans+=dfs(st,en,inf); 50 printf("%d\n",ans); 51 } 52 int main() 53 { 54 int i,a,b,c; 55 while(scanf("%d%d",&n,&m)!=EOF){ 56 memset(map,0,sizeof(map)); 57 for(i=1;i<=n;i++){ 58 scanf("%d%d%d",&a,&b,&c); 59 map[a][b]+=c; 60 } 61 Dinic(1,m); 62 } 63 return 0; 64 }
优化优化,用一下邻接表做...
代码:内存立马减少到了 276k
代码:
1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 #define ma 502 5 #define inf 0x3f3f3f3f 6 using namespace std; 7 int head[ma]; 8 struct node 9 { 10 int to; 11 int w; 12 int next; 13 }; 14 node mat[ma]; 15 int dist[ma]; 16 int pos,n,m; 17 int min(int a,int b){ 18 return a>b?b:a; 19 } 20 void add(int a,int b,int flow){ 21 mat[pos].to=b; 22 mat[pos].w=flow; 23 mat[pos].next=head[a]; 24 head[a]=pos++; 25 } 26 27 bool bfs(int st,int to){ 28 memset(dist,-1,sizeof(int)*(n+1)); 29 queue<int> q; 30 q.push(st); 31 dist[st]=0; 32 int t; 33 while(!q.empty()){ 34 t=q.front(); 35 q.pop(); 36 for(int i=head[t];~i;i=mat[i].next){ 37 if(dist[mat[i].to]<0&&mat[i].w>0){ 38 dist[mat[i].to]=dist[t]+1; 39 if(mat[i].to==to) return 1; 40 q.push(mat[i].to); 41 } 42 } 43 } 44 return 0; 45 } 46 47 int dfs(int st,int to,int flow){ 48 49 int tem=0; 50 if(st==to||flow==0) return flow; 51 for(int i=head[st];~i;i=mat[i].next){ 52 if(mat[i].w>0&&dist[mat[i].to]==dist[st]+1&&(tem=dfs(mat[i].to,to,min(flow,mat[i].w)))) 53 { 54 mat[i].w-=tem; 55 mat[i^1].w+=tem; 56 return tem; 57 } 58 } 59 return 0; 60 } 61 int Dinic(int st,int to){ 62 int ans=0; 63 while(bfs(st,to)) 64 ans+=dfs(st,to,inf); 65 return ans; 66 } 67 68 int main() 69 { 70 int a,b,c; 71 while(scanf("%d%d",&m,&n)!=EOF) 72 { 73 memset(head,-1,sizeof(int)*(n+1)); 74 pos=0; 75 while(m--){ 76 scanf("%d%d%d",&a,&b,&c); 77 add(a,b,c); //单向边 78 add(b,a,0); 79 } 80 printf("%d\n",Dinic(1,n)); 81 } 82 return 0; 83 }
hdu-----(1532)Drainage Ditches(最大流问题)
标签:des style blog http color io os java ar
原文地址:http://www.cnblogs.com/gongxijun/p/3968681.html