题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2444
4 4 1 2 1 3 1 4 2 3 6 5 1 2 1 3 1 4 2 5 3 6
No 3
#include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; bool Map[210][210]; bool vis[210];//是否访问过 int ok[210];//表示链接好 int judge[210];//判断二分图时 0-1表 int n,m; bool Bfs() { queue<int>q; q.push(1);//将第一个点先放进队列里面 //vis[1]=1; for (int i=1; i<=n; i++)//先全部初始化为-1 judge[i]=-1; judge[1]=0;//先将第一个点标记为0 while(!q.empty())//将所有的点都扫描一遍 { int s=q.front(); q.pop(); for(int i=1;i<=n;i++) { if(Map[s][i]==1) { if(judge[i]==-1)//判断是否染色过 { judge[i]=(judge[s]+1)%2;//如果没染过,那就染成与当前点不同的颜色 q.push(i); } else { if(judge[i]==judge[s])//如果染过色,并且与当前点颜色相同,那么就不是二分图 return false; } } } } return true; } /*bool bfs()//数组模拟队列方式 { int v,start=0,end=1; queue[0]=1; for (int i=0; i<=n; i++) judge[i]=-1; v=queue[start]; judge[1]=0; memset(vis,0,sizeof(vis)); while (start<end) { v=queue[start]; for (int i=1; i<=n; i++) { if (Map[v][i]) { if (judge[i]==-1) { judge[i] = (judge[v]+1)%2; queue[end++] = i; } else { if(judge[i] == judge[v]) return false; } } } start++; } return true; } */ bool Find(int x) { for (int i=1; i<=n; i++) { if (Map[x][i]==1&&!vis[i]) { vis[i]=1; if (!ok[i]) { ok[i]=x; return true; } else { if (Find(ok[i])==true) { ok[i]=x; return true; } } } } return false; } int main() { while (~scanf("%d%d",&n,&m)) { int a,b; memset(Map,0,sizeof(Map)); for (int i=1; i<=m; i++) { scanf("%d%d",&a,&b); Map[a][b]=Map[b][a]=1; } if(!Bfs()) { printf("No\n"); continue; } //the maximum number of pair int num = 0; memset(ok,0,sizeof(ok)); for(int i=1; i<=n; i++) { memset(vis,0,sizeof(vis)); if(Find(i)) num++; } printf("%d\n",num/2); } return 0; }