uva 820 Internet Bandwidth (最大流,预流推进)
最大流问题,但是又和最大流不完全相同,
注意点:
(1)它是双向的
(2)两点间路径不唯一
AC不了请参照UVA论坛
//code 1 #include <iostream> #include <cstdio> #include <queue> using namespace std; const int maxn=5000; struct edge{ int u,v,next,c; edge(int u0=0,int v0=0,int c0=0,int next0=0){ u=u0,v=v0,c=c0,next=next0; } }e[maxn*10]; int head[maxn*2],visited[maxn*2],path[maxn*2]; int cnt,from,to,marked,maxflow,offflow,n,casen;; void initial(){ for(int i=0;i<2*maxn;i++){ head[i]=-1; visited[i]=0; } cnt=0; casen++; marked=1; maxflow=0; } void add(int u,int v,int c){ e[cnt].u=u; e[cnt].v=v; e[cnt].c=c; e[cnt].next=head[u]; head[u]=cnt++; } void input(){ int m,a,b,t; cin>>from>>to>>m; while(m-->0){ cin>>a>>b>>t; add(a,b,t); add(b,a,0); add(b,a,t); add(a,b,0); } } bool bfs(){ int s=from,d; queue <int> q; q.push(s); marked++; while(!q.empty()){ s=q.front(); q.pop(); visited[s]=marked; for(int i=head[s];i!=-1;i=e[i].next){ d=e[i].v; if(visited[d]!=marked && e[i].c>0){ visited[d]=marked; path[d]=i; q.push(d); if(d==to) return true; } } } return false; } void computing(){ while(bfs() ){ offflow=maxn; for(int i=to;i!=from;i=e[path[i]].u){ offflow=min(e[path[i]].c,offflow); } for(int i=to;i!=from;i=e[path[i]].u){ e[path[i]].c-=offflow; e[path[i]^1].c+=offflow; } maxflow+=offflow; } printf("Network %d\n",casen); printf("The bandwidth is %d.\n\n",maxflow); } int main(){ while(cin>>n && n){ initial(); input(); computing(); } return 0; }
//code 2 有问题,但是还是AC了 #include <iostream> #include <cstdio> #include <vector> #include <queue> using namespace std; const int maxn=110; vector < vector<int> > bfsmap; int n,cf[maxn][maxn],path[maxn],maxflow,marked,visited[maxn],from,to,m,casen; void initial(){ casen++; bfsmap.clear(); marked=1; for(int i=0;i<=n;i++){ for(int j=0;j<=n;j++){ cf[i][j]=0; } visited[i]=0; } maxflow=0; } void input(){ int u,v,f; bfsmap.resize(n+1); scanf("%d%d%d",&from,&to,&m); for(int i=0;i<m;i++){ scanf("%d%d%d",&u,&v,&f); bfsmap[u].push_back(v); bfsmap[v].push_back(u); cf[u][v]+=f; cf[v][u]+=f; } } bool bfs(){ int s=from,d; queue <int> q; q.push(s); path[s]=s; marked++; while(!q.empty()){ s=q.front(); q.pop(); visited[s]=marked; for(int i=0;i<bfsmap[s].size();i++){ d=bfsmap[s][i]; if(visited[d]!=marked && cf[s][d]>0){ visited[d]=marked; path[d]=s; q.push(d); if(d==to) return true; } } } return false; } void computing(){ while(bfs()){ int offflow=200000000,k=to; while(k!=from){ if(cf[path[k]][k]<offflow) offflow=cf[path[k]][k]; k=path[k]; } maxflow+=offflow; k=to; while(k!=from){ cf[path[k]][k]-=offflow; cf[k][path[k]]-=offflow;//此处有问题 k=path[k]; } } printf("Network %d\n",casen); printf("The bandwidth is %d.\n\n",maxflow); } int main(){ while(scanf("%d",&n)!=EOF && n){ initial(); input(); computing(); } return 0; }