hdu 2444(二分图的判断以及求最大匹配)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2444思路:首先要判断能否构成二分图,用bfs对当前点u染色,对u的邻接点v的颜色进行判断,如果为染色,则染色后入队列,否则,判断color[v]==color[u],如果相等,说明无法构成二部图 ,直接返回false即可。最后就是简单的匈牙利直接求最大匹配就可以了,不过这儿是无向图,最后要除以2。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<queue>
 6 #include<vector>
 7 using namespace std;
 8 #define MAXN 222
 9 vector<int>vet[MAXN];
10 int color[MAXN];
11 bool mark[MAXN];
12 int match[MAXN];
13 int n,m;
14 
15 bool bfs(){
16    queue<int>Q;
17    Q.push(1);mark[1]=true;
18    while(!Q.empty()){
19       int u=Q.front();
20       Q.pop();
21       int c=color[u];
22       for(int i=0;i<vet[u].size();i++){
23          int v=vet[u][i];
24          if(!mark[v]){ mark[v]=true;color[v]=-c;Q.push(v); }
25          else if(color[v]==c)return false;
26       }
27    }
28    return true;
29 }
30 
31 bool dfs(int u){
32    for(int i=0;i<vet[u].size();i++){
33       int v=vet[u][i];
34       if(!mark[v]){
35          mark[v]=true;
36          if(match[v]==-1||dfs(match[v])){
37             match[v]=u;
38             return true;
39          }
40       }
41    }
42    return false;
43 }
44 
45 
46 int MaxMatch(){
47    int res=0;
48    memset(match,-1,sizeof(match));
49    for(int i=1;i<=n;i++){
50       memset(mark,false,sizeof(mark));
51       res+=dfs(i);
52    }
53    return res;
54 }
55 
56 
57 int main(){
58 //   freopen("1.txt","r",stdin);
59    int u,v;
60    while(~scanf("%d%d",&n,&m)){
61       for(int i=1;i<=n;i++)vet[i].clear();
62       for(int i=1;i<=m;i++){
63          scanf("%d%d",&u,&v);
64          vet[u].push_back(v);
65          vet[v].push_back(u);
66       }
67       memset(color,-1,sizeof(color));
68       memset(mark,false,sizeof(mark));
69       if(!bfs()){ puts("No");continue; }
70       int ans=MaxMatch();
71       printf("%d\n",ans/2);
72    }
73    return 0;
74 }
View Code

 

 

posted @ 2013-06-03 21:23  ihge2k  阅读(322)  评论(0编辑  收藏  举报