sgu 194 上下界网络流可行流判定+输出可行流
1 #include <cstdio> 2 #include <cstring> 3 #define min(a,b) ((a)<(b)?(a):(b)) 4 #define oo 0x3f3f3f3f 5 #define N 210 6 #define M 100010 7 8 struct Dinic { 9 int n, src, dst; 10 int head[N], dest[M], flow[M], eid[M], next[M], etot; 11 int cur[N], dep[N], qu[N], bg, ed; 12 13 void init( int n, int src, int dst ) { 14 this->n = n; 15 this->src = src; 16 this->dst = dst; 17 etot = 0; 18 memset( head, -1, sizeof(head) ); 19 } 20 void adde( int id, int u, int v, int f ) { 21 next[etot]=head[u], flow[etot]=f, dest[etot]=v, eid[etot]=id; head[u]=etot++; 22 next[etot]=head[v], flow[etot]=0, dest[etot]=u, eid[etot]=-1; head[v]=etot++; 23 } 24 bool bfs() { 25 memset( dep, 0, sizeof(dep) ); 26 qu[bg=ed=1] = src; 27 dep[src] = 1; 28 while( bg<=ed ) { 29 int u=qu[bg++]; 30 for( int t=head[u]; ~t; t=next[t] ) { 31 int v=dest[t], f=flow[t]; 32 if( f && !dep[v] ) { 33 dep[v] = dep[u]+1; 34 qu[++ed] = v; 35 } 36 } 37 } 38 return dep[dst]; 39 } 40 int dfs( int u, int a ) { 41 if( u==dst || a==0 ) return a; 42 int remain=a, past=0, na; 43 for( int &t=cur[u]; ~t; t=next[t] ) { 44 int v=dest[t], &f=flow[t], &vf=flow[t^1]; 45 if( f && dep[v]==dep[u]+1 && (na=dfs(v,min(remain,f))) ) { 46 f -= na; 47 vf += na; 48 remain -= na; 49 past += na; 50 if( !remain ) break; 51 } 52 } 53 return past; 54 } 55 int maxflow() { 56 int f = 0; 57 while( bfs() ) { 58 for( int u=1; u<=n; u++ ) cur[u]=head[u]; 59 f += dfs(src,oo); 60 } 61 return f; 62 } 63 void print( int *ans ) { 64 for( int e=0; e<etot; e++ ) 65 if( eid[e]!=-1 ) ans[eid[e]]+=flow[e^1]; 66 } 67 }D; 68 struct Bottop { 69 int n; 70 int head[N], dest[M], bot[M], top[M], next[M], eid[M], etot; 71 int si[N], so[N], sum; 72 73 void init( int n ) { 74 this->n = n; 75 memset( head, -1, sizeof(head) ); 76 memset( si, 0, sizeof(si) ); 77 memset( so, 0, sizeof(so) ); 78 etot = 0; 79 } 80 void adde( int id, int u, int v, int b, int t ) { 81 eid[etot]=id, next[etot]=head[u], bot[etot]=b, top[etot]=t, dest[etot]=v; 82 head[u]=etot++; 83 } 84 void build( int *ans ) { 85 int src=n+1, dst=n+2; 86 D.init( dst, src, dst ); 87 for( int u=1; u<=n; u++ ) 88 for( int t=head[u]; ~t; t=next[t] ) { 89 int v=dest[t]; 90 ans[eid[t]] += bot[t]; 91 si[v] += bot[t]; 92 so[u] += bot[t]; 93 D.adde( eid[t], u, v, top[t]-bot[t] ); 94 } 95 for( int u=1; u<=n; u++ ) { 96 if( so[u]>si[u] ) 97 D.adde( -1, u, dst, so[u]-si[u] ); 98 else if( si[u]>so[u] ) { 99 D.adde( -1, src, u, si[u]-so[u] ); 100 sum += si[u]-so[u]; 101 } 102 } 103 } 104 bool ok() { return D.maxflow()==sum; } 105 }B; 106 107 int n, m; 108 int ans[M]; 109 110 int main() { 111 scanf( "%d%d", &n, &m ); 112 B.init(n); 113 for( int i=1,u,v,b,t; i<=m; i++ ) { 114 scanf( "%d%d%d%d", &u, &v, &b, &t ); 115 B.adde( i, u, v, b, t ); 116 } 117 B.build(ans); 118 bool ok = B.ok(); 119 printf( "%s\n", ok ? "YES" : "NO" ); 120 if( ok ) { 121 D.print( ans ); 122 for( int i=1; i<=m; i++ ) 123 printf( "%d\n", ans[i] ); 124 } 125 }