强烈推荐的匈牙利算法介绍:http://www.renfei.org/blog/bipartite-matching.html
1 #include "iostream" 2 #include "vector" 3 #include "memory.h" 4 using namespace std; 5 #define swap(a,b,t) ( (t) = (x),(x) = (y),(y) = (t) ) 6 #define MAXN 1010 7 int l[MAXN][MAXN]; 8 bool flag[MAXN]; 9 int re[MAXN]; 10 int k,m,n; 11 int ans; 12 13 int find(int a) 14 { 15 for (int i = 0;i <= n; ++ i) { 16 if (l[a][i] == 1 && flag[i] == 0) { 17 flag[i] = 1; 18 if (re[i] == 0 || find(re[i])) { 19 re[i] = a; 20 return 1; 21 } 22 } 23 } 24 return 0; 25 } 26 27 void init() 28 { 29 ans = 0; 30 for (int i = 0;i <= m; ++ i) 31 for (int j = 0;j <= n; ++ j) 32 l[i][j] = 0; 33 memset(re,0,sizeof(re)); 34 } 35 36 int main() 37 { 38 39 while (cin >> k,k) { 40 init(); 41 ans = 0; 42 cin >> m >> n; 43 for (int i = 0; i < k; ++ i) { 44 int a,b; 45 cin >> a >> b; 46 l[a][b] = 1; 47 } 48 for(int i = 1;i <= m; ++ i) { 49 memset(flag,0,sizeof(flag)); 50 if (find(i)) ans ++; 51 } 52 cout << ans << endl; 53 } 54 return 0; 55 }
欠一个BFS