基础网络流,增加s和t,同时对于每个结点分裂为流入结点和流出结点。EK求最大流,判断最大流是否等于当前总人数。
1 /* 304E */ 2 #include <iostream> 3 #include <string> 4 #include <map> 5 #include <queue> 6 #include <set> 7 #include <stack> 8 #include <vector> 9 #include <deque> 10 #include <algorithm> 11 #include <cstdio> 12 #include <cmath> 13 #include <ctime> 14 #include <cstring> 15 #include <climits> 16 #include <cctype> 17 #include <cassert> 18 #include <functional> 19 using namespace std; 20 //#pragma comment(linker,"/STACK:102400000,1024000") 21 22 #define rep(i, a, n) for (int i=a;i<n;++i) 23 #define per(i, a, n) for (int i=n-1;i>=a;--i) 24 #define pb push_back 25 #define mp make_pair 26 #define all(x) (x).begin(),(x).end() 27 #define SZ(x) ((int)(x).size()) 28 #define lson l, mid, rt<<1 29 #define rson mid+1, r, rt<<1|1 30 31 const int maxn = 205; 32 int F[maxn][maxn]; 33 int P[maxn], a[maxn]; 34 bool visit[maxn]; 35 int ans[maxn][maxn]; 36 int ai[maxn], bi[maxn], ci[maxn]; 37 int n, m, s = 0, t; 38 bool flag = true; 39 40 bool bfs() { 41 int u, v; 42 queue<int> Q; 43 44 memset(a, 0, sizeof(a)); 45 a[s] = INT_MAX; 46 Q.push(s); 47 P[s] = s; 48 49 while (!Q.empty()) { 50 u = Q.front(); 51 Q.pop(); 52 for (v=0; v<=t; ++v) { 53 if (!a[v] && F[u][v]) { 54 P[v] = u; 55 Q.push(v); 56 a[v] = min(a[u], F[u][v]); 57 } 58 } 59 } 60 61 return a[t]==0; 62 } 63 64 int Edmonds_Karp() { 65 int u, v; 66 int ans = 0; 67 68 while (1) { 69 if (bfs()) 70 break; 71 for (u=t,v=P[u]; u!=s; u=v, v=P[u]) { 72 F[u][v] += a[t]; 73 F[v][u] -= a[t]; 74 } 75 ans += a[t]; 76 } 77 return ans; 78 } 79 80 int main() { 81 int i, j, k; 82 int s1, s2; 83 84 #ifndef ONLINE_JUDGE 85 freopen("data.in", "r", stdin); 86 freopen("data.out", "w", stdout); 87 #endif 88 89 scanf("%d %d", &n, &m); 90 t = n+n+1; 91 memset(F, 0, sizeof(F)); 92 memset(ans, 0, sizeof(ans)); 93 s1 = s2 = 0; 94 95 for (i=1; i<=n; ++i) { 96 scanf("%d", &ai[i]); 97 s1 += ai[i]; 98 F[0][i] = ai[i]; 99 } 100 101 for (i=1; i<=n; ++i) { 102 scanf("%d", &bi[i]); 103 s2 += bi[i]; 104 F[i][i+n] = INT_MAX; 105 F[i+n][t] = bi[i]; 106 } 107 108 for (i=0; i<m; ++i) { 109 scanf("%d %d", &j, &k); 110 F[j][k+n] = INT_MAX; 111 F[k][j+n] = INT_MAX; 112 } 113 114 flag = s1==s2; 115 if (flag) { 116 flag = Edmonds_Karp() == s1; 117 } 118 119 if (flag) { 120 for (i=1; i<=n; ++i) 121 for (j=n+1; j<t; ++j) 122 ans[i][j-n] = F[j][i]; 123 puts("YES"); 124 for (i=1; i<=n; ++i) { 125 for (j=1; j<=n; ++j) 126 printf("%d ", ans[i][j]); 127 putchar(‘\n‘); 128 } 129 } else { 130 puts("NO"); 131 } 132 133 #ifndef ONLINE_JUDGE 134 printf("time = %d.\n", (int)clock()); 135 #endif 136 137 return 0; 138 }
时间: 2024-10-11 21:17:47