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
|
#include <bits/stdc++.h> using namespace std; #define int long long #define resetIO(x) \ freopen(#x ".in", "r", stdin), freopen(#x ".out", "w", stdout) #define debug(fmt, ...) \ fprintf(stderr, "[%s:%d] " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__) template <class _Tp> inline _Tp& read(_Tp &x) { bool sign = false; char ch = getchar(); long double tmp = 1; for (; !isdigit(ch); ch = getchar()) sign |= (ch == '-'); for (x = 0; isdigit(ch); ch = getchar()) x = x * 10 + (ch ^ 48); if (ch == '.') for (ch = getchar(); isdigit(ch); ch = getchar()) tmp /= 10.0, x += tmp * (ch ^ 48); return sign ? (x = -x) : x; } template <class _Tp> inline void write(_Tp x) { if (x < 0) putchar('-'), x = -x; if (x > 9) write(x / 10); putchar((x % 10) ^ 48); } const int MAXN = 350; const int MAXM = 1e5 + 10; const int INF = 0x3f3f3f3f3f3f3f3f; struct dinic { struct edges { int v, w, next; } edge[MAXM]; int n, tot, head[MAXN]; int cur[MAXN], lev[MAXN]; void init(int n) { this->n = n, tot = 0; fill(head, head + n + 1, -1); } void addedge(int u, int v, int w) { edge[tot] = {v, w, head[u]}; head[u] = tot++; edge[tot] = {u, 0, head[v]}; head[v] = tot++; } bool bfs(int s, int t) { fill(lev, lev + n + 1, -1); queue<int> que; que.push(s), lev[s] = 0; while (!que.empty()) { int u = que.front(); que.pop(); for (int i = head[u]; ~i; i = edge[i].next) { if (edge[i].w && lev[edge[i].v] == -1) { lev[edge[i].v] = lev[u] + 1; que.push(edge[i].v); } } } return lev[t] != -1; } int dfs(int u, int t, int mx) { if (u == t || mx == 0) return mx; int ret = 0; for (int &i = cur[u]; ~i; i = edge[i].next) { int v = edge[i].v, w = edge[i].w; if (lev[v] != lev[u] + 1) continue; int tmp = dfs(v, t, min(mx, w)); edge[i].w -= tmp, edge[i ^ 1].w += tmp; mx -= tmp, ret += tmp; if (mx == 0) break; } return ret; } int maxflow(int s, int t) { int ret = 0; while (bfs(s, t)) { copy(head, head + n + 1, cur); ret += dfs(s, t, INF); } return ret; } }; int n, m, s, t; dinic nf; signed main() { read(m), read(n); s = n + 1, t = n + 2; nf.init(n + 2); for (int i = 1; i <= m; ++i) nf.addedge(s, i, 1); for (int i = m + 1; i <= n; ++i) nf.addedge(i, t, 1); int u, v; while (scanf("%lld%lld", &u, &v), u != -1 && v != -1) nf.addedge(u, v, INF); write(nf.maxflow(s, t)), putchar('\n'); for (int i = 0; i < nf.tot; i += 2) if (nf.edge[i].w == INF - 1) printf("%lld %lld\n", nf.edge[i ^ 1].v, nf.edge[i].v); return 0; }
|