匈牙利算法+sort
没什么好说的。
——代码
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 5 using namespace std; 6 7 int n, m, cnt, sum; 8 int next[10001], head[101], to[10001]; 9 bool vis[101]; 10 struct node 11 { 12 int k, b; 13 }g[101]; 14 15 bool cmp(node x, node y) 16 { 17 return x.b < y.b; 18 } 19 20 void add(int x, int y) 21 { 22 to[cnt] = y; 23 next[cnt] = head[x]; 24 head[x] = cnt++; 25 } 26 27 bool find(int u) 28 { 29 int i, v; 30 for(i = head[u]; i != -1; i = next[i]) 31 { 32 v = to[i]; 33 if(!vis[v]) 34 { 35 vis[v] = 1; 36 if(!g[v].b || find(g[v].b)) 37 { 38 g[v].b = u; 39 g[v].k = v; 40 return 1; 41 } 42 } 43 } 44 return 0; 45 } 46 47 int main() 48 { 49 int i, x, y; 50 scanf("%d %d", &m, &n); 51 memset(head, -1, sizeof(head)); 52 while(scanf("%d %d", &x, &y) && x != -1 && y != -1) add(x, y); 53 //匈牙利 54 for(i = 1; i <= m; i++) 55 { 56 memset(vis, 0, sizeof(vis)); 57 if(find(i)) sum++; 58 } 59 if(!sum) 60 { 61 printf("No Solution!"); 62 return 0; 63 } 64 printf("%d ", sum); 65 sort(g + 1, g + n + 1, cmp); 66 for(i = 1; i <= n; i++) 67 { 68 if(!g[i].b || !g[i].k) continue; 69 printf("%d %d ", g[i].b, g[i].k); 70 } 71 return 0; 72 }