标签:
诈个尸。
二分图匹配。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <queue> 6 using namespace std; 7 const int INF = 1e9; 8 const int maxn = 2e5 + 10; 9 int lv[maxn], it[maxn]; 10 int cnt, h[maxn]; 11 12 struct edge 13 { 14 int to, pre, cap; 15 } e[maxn<<1]; 16 17 void init() 18 { 19 memset(h, -1, sizeof(h)); 20 cnt = 0; 21 } 22 23 void add(int from, int to, int cap) 24 { 25 e[cnt].pre = h[from]; 26 e[cnt].to = to; 27 e[cnt].cap = cap; 28 h[from] = cnt; 29 cnt++; 30 } 31 32 void ad(int from, int to, int cap) 33 { 34 add(from, to, cap); 35 add(to, from, 0); 36 } 37 38 void bfs(int s) 39 { 40 memset(lv, -1, sizeof(lv)); 41 queue<int> q; 42 lv[s] = 0; 43 q.push(s); 44 while(!q.empty()) 45 { 46 int v = q.front(); q.pop(); 47 for(int i = h[v]; i >= 0; i = e[i].pre) 48 { 49 int cap = e[i].cap, to = e[i].to; 50 if(cap > 0 && lv[to] < 0) 51 { 52 lv[to] = lv[v] + 1; 53 q.push(to); 54 } 55 } 56 } 57 } 58 59 int dfs(int v, int t, int f) 60 { 61 if(v == t) return f; 62 for(int &i = it[v]; i >= 0; i = e[i].pre) 63 { 64 int &cap = e[i].cap, to = e[i].to; 65 if(cap > 0 && lv[v] < lv[to]) 66 { 67 int d = dfs(to, t, min(f, cap)); 68 if(d > 0) 69 { 70 cap -= d; 71 e[i^1].cap += d; 72 return d; 73 } 74 } 75 } 76 return 0; 77 } 78 79 int Dinic(int s, int t) 80 { 81 int flow = 0; 82 while(1) 83 { 84 bfs(s); 85 if(lv[t] < 0) return flow; 86 memcpy(it, h, sizeof(it)); 87 int f; 88 while((f = dfs(s, t, INF)) > 0) flow += f; 89 } 90 } 91 92 int main(void) 93 { 94 init(); 95 int m, n; 96 scanf("%d %d", &m, &n); 97 while(1) 98 { 99 int u, v; 100 scanf("%d %d", &u, &v); 101 if(u == -1) break; 102 ad(u, v, 1); 103 } 104 int S = n + 1, T = S + 1; 105 for(int i = 1; i <= m; i++) ad(S, i, 1); 106 for(int i = m + 1; i <= n; i++) ad(i, T, 1); 107 int ans = Dinic(S, T); 108 if(!ans) puts("No Solution!"); 109 else 110 { 111 printf("%d\n", ans); 112 for(int i = 1; i <= m; i++) 113 for(int j = h[i]; j != -1; j = e[j].pre) 114 if(e[j].to <= n && !e[j].cap) printf("%d %d\n", i, e[j].to); 115 } 116 return 0; 117 }
标签:
原文地址:http://www.cnblogs.com/Aguin/p/5396674.html