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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| #include <cstdio> #include <queue> using namespace std; const int N = 1e3 + 10, M = 1e5 + 10; queue<int> q; int stmp, vis[N]; int n, m, c[N], f[N], p[N], match[N]; int idx, hd[N], nxt[M], edg[M]; int fa(int x) { return p[x] == x ? x : p[x] = fa(p[x]); } int LCA(int x, int y) { stmp++; while (true) { if (!x) { swap(x, y); continue; } x = fa(x); if (vis[x] == stmp) return x; vis[x] = stmp; x = f[match[x]]; swap(x, y); } } void blossom(int x, int y, int lca) { while (fa(x) != lca) { f[x] = y, y = match[x]; if (c[y] == 2) { c[y] = 1; q.push(y); } if (fa(x) == x) p[x] = lca; if (fa(y) == y) p[y] = lca; x = f[y]; } } bool bfs(int st) { for (int i = 1; i <= n; i++) c[i] = f[i] = 0, p[i] = i; while (!q.empty()) q.pop(); q.push(st); c[st] = 1; while (!q.empty()) { int t = q.front(); q.pop(); for (int i = hd[t]; ~i; i = nxt[i]) { if (fa(t) == fa(edg[i]) || c[edg[i]] == 2) continue; if (!c[edg[i]]) { c[edg[i]] = 2; f[edg[i]] = t; if (!match[edg[i]]) { for (int j = edg[i], x; j; j = x) { x = match[f[j]]; match[j] = f[j]; match[f[j]] = j; } return true; } else { c[match[edg[i]]] = 1; q.push(match[edg[i]]); } } else { int lca = LCA(t, edg[i]); blossom(t, edg[i], lca); blossom(edg[i], t, lca); } } } return false; } void add(int a, int b) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) hd[i] = -1; for (int u, v; m; m--) { scanf("%d%d", &u, &v); add(u, v); add(v, u); } int res = 0; for (int i = 1; i <= n; i++) if (!match[i]) res += bfs(i); printf("%d\n", res); for (int i = 1; i <= n; i++) printf("%d ", match[i]); return 0; }
|