Reactor Cooling ZOJ - 2314 上下界网络流

时间:2024-10-03 18:05:38

Code:

#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<iostream>
#include<cstring>
using namespace std;
const int maxn=600;
const int INF=1000000;
# define pb push_back
int A[maxn],mapp[INF],bass[INF];
int s,t;
struct Edge{
int from,to,cap;
Edge(int u,int v,int c):from(u),to(v),cap(c) {}
};
vector<Edge>edges;
struct Dicnic{
vector<int>G[maxn];
int d[maxn],vis[maxn],cur[maxn];
queue<int>Q;
void init(){
for(int i=0;i<maxn;++i)G[i].clear();
edges.clear();
}
void addedge(int u,int v,int c,int cnt){
edges.pb(Edge(u,v,c)); //正向弧
edges.pb(Edge(v,u,0)); //反向弧
int m=edges.size();
G[u].pb(m-2);
G[v].pb(m-1);
if(cnt>0)mapp[cnt]=m-1;
}
int BFS()
{
memset(vis,0,sizeof(vis));
d[s]=0,vis[s]=1;Q.push(s);
while(!Q.empty()){
int u=Q.front();Q.pop();
int sz=G[u].size();
for(int i=0;i<sz;++i){
Edge e=edges[G[u][i]];
if(!vis[e.to]&&e.cap>0){
d[e.to]=d[u]+1,vis[e.to]=1;
Q.push(e.to);
}
}
}
return vis[t];
}
int dfs(int x,int a){
if(x==t)return a;
int sz=G[x].size();
int f,flow=0;
for(int i=cur[x];i<sz;++i){
Edge e=edges[G[x][i]];
cur[x]=i;
if(d[e.to]==d[x]+1&&e.cap>0){
f=dfs(e.to,min(a,e.cap));
if(f)
{
int u=G[x][i];
a-=f;
edges[u].cap-=f;
edges[u^1].cap+=f;
flow+=f;
if(a==0)break;
}
}
}
return flow;
}
int maxflow(){
int ans=0;
while(BFS()){
memset(cur,0,sizeof(cur));
ans+=dfs(s,INF);
}
return ans;
}
}op;
int main(){
int T;cin>>T;
s=0,t=420;
for(int cas=1;cas<=T;++cas){
memset(A,0,sizeof(A));
op.init();
int n,m,sum=0;
cin>>n>>m;
for(int i=1;i<=m;++i){
int a,b,c,d;
cin>>a>>b>>c>>d;
bass[i]=c;
op.addedge(a,b,d-c,i);
A[a]-=c,A[b]+=c;
}
for(int i=1;i<=m;++i){
if(A[i]>0){op.addedge(s,i,A[i],0);sum+=A[i];}
if(A[i]<0)op.addedge(i,t,-A[i],0);
}
int flow=op.maxflow();
if(flow==sum){
cout<<"YES"<<endl;
for(int i=1;i<m;++i)cout<<edges[mapp[i]].cap+bass[i]<<endl;
cout<<edges[mapp[m]].cap+bass[m];
if(cas!=T)cout<<endl;
}else cout<<"NO"<<endl;
if(cas!=T)cout<<endl;
}
return 0;
}