[CODEVS1914] 运输问题(最小费用最大流)
水题。
建图都不想说了
——代码
1 #include <queue> 2 #include <cstdio> 3 #include <cstring> 4 #include <iostream> 5 #define INF 1e9 6 #define M 101 7 #define N 100001 8 #define min(x, y) ((x) < (y) ? (x) : (y)) 9 10 int n, m, cnt, s, t; 11 int a[M], b[M], map[M][M], dis[N], pre[N]; 12 int head[N], to[N << 1], val[N << 1], cost[N << 1], next[N << 1]; 13 bool vis[N]; 14 15 inline int read() 16 { 17 int x = 0, f = 1; 18 char ch = getchar(); 19 for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = -1; 20 for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0'; 21 return x * f; 22 } 23 24 inline void add(int x, int y, int z, int c) 25 { 26 to[cnt] = y; 27 val[cnt] = z; 28 cost[cnt] = c; 29 next[cnt] = head[x]; 30 head[x] = cnt++; 31 } 32 33 inline bool spfa() 34 { 35 int i, u, v; 36 std::queue <int> q; 37 memset(vis, 0, sizeof(vis)); 38 memset(pre, -1, sizeof(pre)); 39 memset(dis, 127 / 3, sizeof(dis)); 40 q.push(s); 41 dis[s] = 0; 42 while(!q.empty()) 43 { 44 u = q.front(), q.pop(); 45 vis[u] = 0; 46 for(i = head[u]; i ^ -1; i = next[i]) 47 { 48 v = to[i]; 49 if(val[i] && dis[v] > dis[u] + cost[i]) 50 { 51 dis[v] = dis[u] + cost[i]; 52 pre[v] = i; 53 if(!vis[v]) 54 { 55 q.push(v); 56 vis[v] = 1; 57 } 58 } 59 } 60 } 61 return pre[t] ^ -1; 62 } 63 64 inline int dinic() 65 { 66 int i, d, sum = 0; 67 while(spfa()) 68 { 69 d = 1e9; 70 for(i = pre[t]; i ^ -1; i = pre[to[i ^ 1]]) d = min(d, val[i]); 71 for(i = pre[t]; i ^ -1; i = pre[to[i ^ 1]]) 72 { 73 val[i] -= d; 74 val[i ^ 1] += d; 75 } 76 sum += dis[t] * d; 77 } 78 return sum; 79 } 80 81 int main() 82 { 83 int i, j; 84 m = read(); 85 n = read(); 86 s = 0, t = n + m + 1; 87 memset(head, -1, sizeof(head)); 88 for(i = 1; i <= m; i++) 89 { 90 a[i] = read(); 91 add(s, i, a[i], 0); 92 add(i, s, 0, 0); 93 } 94 for(i = 1; i <= n; i++) 95 { 96 b[i] = read(); 97 add(i + m, t, b[i], 0); 98 add(t, i + m, 0, 0); 99 } 100 for(i = 1; i <= m; i++) 101 for(j = 1; j <= n; j++) 102 { 103 map[i][j] = read(); 104 add(i, j + m, INF, map[i][j]); 105 add(j + m, i, 0, -map[i][j]); 106 } 107 printf("%d\n", dinic()); 108 cnt = 0; 109 memset(head, -1, sizeof(head)); 110 for(i = 1; i <= m; i++) 111 { 112 add(s, i, a[i], 0); 113 add(i, s, 0, 0); 114 } 115 for(i = 1; i <= n; i++) 116 { 117 add(i + m, t, b[i], 0); 118 add(t, i + m, 0, 0); 119 } 120 for(i = 1; i <= m; i++) 121 for(j = 1; j <= n; j++) 122 { 123 add(i, j + m, INF, -map[i][j]); 124 add(j + m, i, 0, map[i][j]); 125 } 126 printf("%d\n", -dinic()); 127 return 0; 128 }