1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #include <iostream> #include <cstdio> #include <cstring> #include <queue> #define MAX_N 300 #define MAX_M MAX_N*(MAX_N-1)*2 #define INF 2147483647 using namespace std; int n, m, s, t; int d[MAX_N+5], first[MAX_N+5], cnt; struct node {int v, c, next;} E[MAX_M+5]; void Init() { cnt = 0; memset(first, -1, sizeof(first)); } void Insert(int u, int v, int c) { E[cnt].v = v, E[cnt].c = c; E[cnt].next = first[u]; first[u] = cnt++; } void AddEdge(int u, int v, int c) { Insert(u, v, c); Insert(v, u, 0); } bool BFS() { memset(d, -1, sizeof(d)); queue <int> que; que.push(s), d[s] = 0; while (!que.empty()) { int u = que.front(); for (int i = first[u]; i != -1; i = E[i].next) { int v = E[i].v; if (E[i].c && d[v] == -1) { d[v] = d[u]+1; que.push(v); } } que.pop(); } return (d[t] != -1); } int DFS(int u, int flow) { if (u == t) return flow; int ret = 0; for (int i = first[u]; i != -1; i = E[i].next) { int v = E[i].v; if (E[i].c && d[v] == d[u]+1) { int tmp = DFS(v, min(flow, E[i].c)); if (!tmp) continue; flow -= tmp, E[i].c -= tmp; ret += tmp, E[i^1].c += tmp; if (!flow) break; } } if (!ret) d[u] = -1; return ret; } int Dinic() { int ret = 0; while (BFS()) ret += DFS(s, INF); return ret; } int main() { Init(); scanf("%d%d", &n, &m); s = 0, t = n+1; for (int i = 1; i <= n; i++) { int f; scanf("%d", &f); if (f == 1) { AddEdge(s, i, 1); } else { AddEdge(i, t, 1); } } for (int i = 0; i < m; i++) { int u, v; scanf("%d%d", &u, &v); AddEdge(u, v, 1); AddEdge(v, u, 1); } printf("%d", Dinic()); return 0; }
|