無源匯上下界可行流
阿新 • • 發佈:2020-11-29
ACWing 2188
#include<iostream> #include<string> #include<cstring> #include<algorithm> #include<queue> using namespace std; const int N = 200 + 10; const int M = 10200 + N + 10 << 1; const int INF = 0x3f3f3f3f; int n,m,s,t; int h[N], e[M],ne[M],idx,w[M],cmin[M]; int gap[N],deepth[N],all[N];void add(int a,int b,int c,int d) { e[idx] = b,ne[idx] = h[a],w[idx] = d-c,cmin[idx] = c,h[a] = idx++; swap(a,b),c = d= 0; e[idx] = b,ne[idx] = h[a],w[idx] = d-c,cmin[idx] = c,h[a] = idx++; } void bfs() { queue<int>q; memset(gap,0,sizeof(gap)); memset(deepth,-1,sizeof(deepth)); q.push(t); deepth[t]= 0; gap[0] = 1; while(q.size()) { int a = q.front(); q.pop(); for(int i = h[a];~i;i = ne[i]) { int j = e[i]; if(deepth[j] == -1) { deepth[j] = deepth[a] + 1; gap[deepth[j]]++; } } } }int dfs(int now,int flow) { if(now == t) return flow; int nowflow = 0; for(int i = h[now];~i;i = ne[i]) { int j = e[i]; if(w[i]&&deepth[j] + 1 == deepth[now]) { int k = dfs(j,min(flow - nowflow,w[i])); w[i]-=k,w[i^1]+=k,nowflow+=k; if(nowflow == flow) return flow; } } --gap[deepth[now]]; if(!gap[deepth[now]]) gap[s] = n+2; ++deepth[now]; ++gap[deepth[now]]; return nowflow; } int ISAP() { int ans = 0; bfs(); while(gap[s]<n) ans += dfs(s,INF); return ans; } int main() { memset(h,-1,sizeof(h));idx = 0; cin >> n >> m; s = 0, t = N-1; int T = m; while(T--) { int a,b,c,d; cin >> a >> b >> c >> d; add(a,b,c,d); all[a]-=c,all[b]+=c; } int tot = 0; for(int i = 1;i<=n;i++) { if(all[i]>0) add(s,i,0,all[i]),tot +=all[i]; else add(i,t,0,-all[i]); } if(ISAP()!=tot) cout << "NO" << endl; else { cout << "YES" << endl; for(int i = 0;i<m*2;i+=2) cout << cmin[i] + w[i^1] << endl; } return 0; }