SGU 194 Reactor Cooling
没有源点和汇点、流量有上下界的网络可行流问题。
今天看了一下午的有上下界的网络可行流问题,在似懂非懂、非常朦胧的状态下过了这个题...激动了半天。
求解的方法:http://www.cnblogs.com/zufezzt/p/4681035.html
AC代码:
#include<cstdio> #include<cstring> #include<string> #include<cmath> #include<vector> #include<queue> #include<algorithm> using namespace std; const int maxn=1000+10; const int INF=0x7FFFFFFF; struct Edge { int from,to,cap,flow,up,low; }; vector<Edge>edges; vector<int>G[maxn]; bool vis[maxn]; int d[maxn]; int cur[maxn]; int Out[maxn],In[maxn]; int s,t; //求出层次网络 bool BFS() { memset(vis,0,sizeof(vis)); queue<int>Q; Q.push(s); d[s]=0; vis[s]=1; while(!Q.empty()) { int x=Q.front(); Q.pop(); for(int i=0; i<G[x].size(); i++) { Edge& e=edges[G[x][i]]; if(!vis[e.to]&&e.cap>e.flow) { vis[e.to]=1; d[e.to]=d[x]+1; Q.push(e.to); } } } return vis[t]; } //加边 void AddEdge(int from,int to,int low,int up) { int m; Edge r; r.from=from; r.to=to; r.cap=up-low; r.flow=0; r.low=low; r.up=up; edges.push_back(r); Edge d; d.from=to; d.to=from; d.cap=0; d.flow=0; //r.low=low;r.up=up; edges.push_back(d); m=edges.size(); G[from].push_back(m-2); G[to].push_back(m-1); } //每个阶段来一次DFS增广 int DFS(int x,int a) { if(x==t||a==0) return a; int flow=0,f; for(int i=cur[x]; i<G[x].size(); i++) { Edge& e=edges[G[x][i]]; if(d[x]+1==d[e.to]&&(f=DFS(e.to,min(a,e.cap-e.flow)))>0) { e.flow+=f; edges[G[x][i]^1].flow-=f; flow+=f; a-=f; if(a==0) break; } } return flow; } //多个阶段,多次建立层次网络。 int Maxflow(int ss,int tt) { int flow=0; while(BFS()) { memset(cur,0,sizeof(cur)); flow+=DFS(ss,INF); } return flow; } int main() { int N,M,i,j; while(~scanf("%d%d",&N,&M)) { edges.clear(); for(int i=0; i<maxn; i++) G[i].clear(); memset(In,0,sizeof(In)); memset(Out,0,sizeof(Out)); s=0; t=N+1; for(i=1; i<=M; i++) { int u,v,low,up; scanf("%d%d%d%d",&u,&v,&low,&up); AddEdge(u,v,low,up); In[v]=In[v]+low; Out[u]=Out[u]+low; } for(i=1; i<=N; i++) { AddEdge(i,t,0,Out[i]); AddEdge(s,i,0,In[i]); } Maxflow(s,t); int flag=1; for(i=0; i<edges.size(); i++) if(edges[i].from==s) if(edges[i].flow<edges[i].cap) { flag=0; break; } if(!flag) printf("NO\n"); else { printf("YES\n"); for(i=0; i<2*M; i++) if(i%2==0) printf("%d\n",edges[i].flow+edges[i].low); } } return 0; }