题目:http://acm.hdu.edu.cn/showproblem.php?pid=2063
1 #include<iostream>
2 #include<math.h>
3 #include<stdio.h>
4 #include<string.h>
5 #include<stdlib.h>
6 using namespace std;
7 const int N=510;
8 int match[N];
9 int a[N][N];
10 int use[N];
11 int n;
12 int girl,boy;
13 int dfs(int u)
14 {
15 int t,x;
16 for(int i=1;i<=boy;i++)
17 {
18 x=a[u][i];//判断是否女孩喜欢这个男孩坐旁边
19 if(x==1 && !use[i])
20 {
21 use[i]=1;//判断是否已匹配,无匹配赋值1
22 t=match[i];//用t标记男孩的匹配,用于后面的判断
23 match[i]=u;//强制将男孩的匹配更改到当前女孩的身上
24 if(t==-1 || dfs(t))//由于可能强制更改了男孩的匹配,那么男孩原来匹配的女孩
25 return 1; //也是需要在另找一个她愿意的男孩进行匹配(dfs)
26 match[i]=t;//如果找不到的话,那么当前的女孩是不能夺走男孩的
27 }
28 }
29 return 0;
30 }
31 int bipartite()
32 {
33 int res=0;
34 memset(match,-1,sizeof(match));//上来初始化男孩的匹配都是-1
35 for(int i=1;i<=girl;i++)
36 {
37 memset(use,0,sizeof(use));//针对每个女孩,男孩是否和他们匹配了
38 if(dfs(i))
39 res++;
40 }
41 return res;
42 }
43
44 int main()
45 {
46 //freopen("in.txt","r",stdin);
47 int p,q;
48 while(~scanf("%d",&n))
49 {
50 if(!n)
51 break;
52 scanf("%d%d",&girl,&boy);//女孩和男孩的数量
53 memset(a,0,sizeof(a));
54 for(int i=0;i<n;i++)
55 {
56 scanf("%d%d",&p,&q);
57 a[p][q]=1;//标记上女孩的喜好
58 }
59 int t=bipartite();
60 printf("%d\n",t);
61 }
62 return 0;
63 }