标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 14375 Accepted Submission(s): 6810
#include <iostream> #include <queue> #include<string.h> #include<algorithm> #include<stdio.h> using namespace std; const int N = 205; const int INF = 999999999; int flow[N]; ///标记从源点到当前节点实际还剩多少流量可用 int cap[N][N]; ///记录残留网络的容量 int pre[N]; ///记录前结点,为寻找路径做准备 int n,m; int BFS(int src,int des) { queue<int> q; for(int i=1; i<=m; i++) { pre[i]=-1; } pre[src] = 0; flow[src] = INF; q.push(src); while(!q.empty()) { int u = q.front(); q.pop(); if(u==des) break; for(int i=1; i<=m; i++) { if(i!=src&&cap[u][i]>0&&pre[i]==-1) { pre[i] = u; flow[i] = min(cap[u][i],flow[u]); q.push(i); } } } if(pre[des]==-1) return -1;///没有增广路了 return flow[des]; } void max_flow(int src,int des) { int increaseRoad = 0; int MAXFLOW = 0; while((increaseRoad=BFS(src,des))!=-1) { int k = des; while(k!=src) { cap[pre[k]][k]-=increaseRoad; ///正向边的容量 cap[k][pre[k]]+=increaseRoad; ///反向边的容量 k = pre[k]; } MAXFLOW+=increaseRoad; } printf("%d\n",MAXFLOW); } int main() { while(scanf("%d%d",&n,&m)!=EOF) { memset(cap,0,sizeof(cap)); for(int i=0; i<n; i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w); if(u==v) continue; cap[u][v]+=w; } max_flow(1,m); } return 0; }
Dinic算法模板:http://blog.csdn.net/wall_f/article/details/8207595
#include <iostream> #include <queue> #include<string.h> #include<algorithm> #include<stdio.h> using namespace std; const int N = 205; const int INF = 999999999; struct Edge{ int v,w,next; }edge[N*N]; int head[N]; int level[N]; int n,m; void addEdge(int u,int v,int w,int &k){ edge[k].v = v,edge[k].w=w,edge[k].next=head[u],head[u]=k++; edge[k].v = u,edge[k].w=0,edge[k].next=head[v],head[v]=k++; ///建立反向边 } int BFS(int src,int des){ queue<int >q; memset(level,0,sizeof(level)); level[src]=1; q.push(src); while(!q.empty()){ int u = q.front(); q.pop(); if(u==des) return 1; for(int k = head[u];k!=-1;k=edge[k].next){ int v = edge[k].v,w=edge[k].w; if(level[v]==0&&w!=0){ level[v]=level[u]+1; q.push(v); } } } return -1; } int dfs(int u,int des,int increaseRoad){ if(u==des) return increaseRoad; int ret=0; for(int k=head[u];k!=-1;k=edge[k].next){ int v = edge[k].v,w=edge[k].w; if(level[v]==level[u]+1&&w!=0){ int MIN = min(increaseRoad-ret,w); w = dfs(v,des,MIN); edge[k].w -=w; edge[k^1].w+=w; ret+=w; if(ret==increaseRoad) return ret; } } return ret; } int Dinic(int src,int des){ int ans = 0; while(BFS(src,des)!=-1) ans+=dfs(src,des,INF); return ans; } int main() { while(scanf("%d%d",&n,&m)!=EOF) { memset(head,-1,sizeof(head)); int tot = 0; for(int i=0;i<n;i++){ int u,v,w; scanf("%d%d%d",&u,&v,&w); if(u==v) continue; addEdge(u,v,w,tot); } printf("%d\n",Dinic(1,m)); } return 0; }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5545166.html