poj 1459 最大流(dinic实现)
1 #include <iostream> 2 #include <cstring> 3 4 #define N 1005 5 #define M 50005 6 #define I 0x7fffffff 7 using namespace std; 8 struct edge{ 9 int next, val, e; 10 }net[M]; 11 int p[N], que[N], lev[N]; 12 int ind; 13 inline void build (int s, int e, int w) { 14 net[ind].e = e; 15 net[ind].val = w; 16 net[ind].next = p[s]; 17 p[s] = ind++; 18 net[ind].e = s; 19 net[ind].val = 0; 20 net[ind].next = p[e]; 21 p[e] = ind++; 22 } 23 int dinic (int start, int end) { 24 int t, path_n, k, i, h, r; 25 int cur[M], path[M]; 26 int maxflow = 0; 27 while (true) { 28 memset (lev, 0, sizeof (lev) ); 29 h = r = 0; 30 lev[start] = 1; 31 que[0] = start; 32 while (h <= r) { 33 int t = que[h++]; 34 for (i = p[t];i != -1;i = net[i].next) { 35 if (net[i].val && lev[net[i].e] == 0) { 36 lev[net[i].e] = lev[t] + 1; 37 que[++r] = net[i].e; 38 } 39 } 40 } 41 if (lev[end] == 0) 42 break; 43 memcpy (cur, p, sizeof (p) ); 44 path_n = -1; 45 while (true) { 46 if (path_n < 0) { 47 i = cur[start]; 48 for (;i != -1;i = net[i].next) { 49 if (net[i].val && cur[net[i].e] != -1 50 && lev[net[i].e] == 2) 51 break; 52 } 53 if (i >= 0) { 54 path[++path_n] = i; 55 cur[start] = net[i].next; 56 } 57 else 58 break; 59 } 60 t = net[path[path_n]].e; 61 if (t == end) { 62 int mink = -1; 63 int mmin = I; 64 for (k = 0;k <= path_n;k++) { 65 if (net[path[k]].val < mmin) { 66 mink = k; 67 mmin = net[path[k]].val; 68 } 69 } 70 maxflow += mmin; 71 for (k = 0;k <= path_n;k++) { 72 net[path[k]].val -= mmin; 73 net[path[k] ^ 1].val += mmin; 74 } 75 for (k = 0;k <= path_n;k++) { 76 if (net[path[k]].val == 0) { 77 path_n = mink - 1; 78 break; 79 } 80 } 81 } 82 else{ 83 i = cur[t]; 84 for (;i != -1;i = net[i].next) { 85 if (net[i].val && cur[net[i].e] != -1 86 && lev[net[i].e] == lev[t] + 1) 87 break; 88 } 89 if (i != -1) { 90 path[++path_n] = i; 91 cur[t] = net[i].next; 92 } 93 else{ 94 cur[t] = -1; 95 path_n--; 96 } 97 } 98 } 99 } 100 return maxflow; 101 } 102 int main (void) 103 { 104 int n,m,np,nc; 105 int flag[105]; 106 int insum[105]; 107 char tmp[30]; 108 while (~scanf("%d%d%d%d",&n,&np,&nc,&m)) { 109 memset (p, -1, sizeof (p) ); 110 ind = 0; 111 memset(flag,0,sizeof(flag)); 112 memset(insum,0,sizeof(insum)); 113 int u,v,z; 114 for(int i=0; i<m; i++) 115 { 116 scanf("%s",tmp); 117 sscanf(tmp,"(%d,%d)%d",&u,&v,&z); 118 u++,v++; 119 build(u+n,v,z); 120 insum[v] += z; 121 } 122 123 for(int i=0; i<np; i++) 124 { 125 scanf("%s",tmp); 126 sscanf(tmp,"(%d)%d",&u,&z); 127 u++; 128 flag[u] = 1; 129 build(0,u,z); 130 } 131 132 for(int i=0; i<nc; i++) 133 { 134 scanf("%s",tmp); 135 sscanf(tmp,"(%d)%d",&u,&z); 136 u++; 137 flag[u] = 2; 138 build(u+n,2*n+1,z); 139 } 140 141 for(int i=1; i<=n; i++) 142 build(i,i+n,I); 143 printf("%d\n",dinic(0,2*n+1)); 144 } 145 return 0; 146 }