您的位置:首页 > 其它

二分图最大匹配各种题型

2016-05-23 12:18 316 查看
Description

There are a group of students. Some of them may know each other, while others don't. For example, A and B know each other, B and C know each other. But this may not imply that A and C know each other.

Now you are given all pairs of students who know each other. Your task is to divide the students into two groups so that any two students in the same group don't know each other.If this goal can be achieved, then arrange them into double rooms. Remember, only
paris appearing in the previous given set can live in the same room, which means only known students can live in the same room.

Calculate the maximum number of pairs that can be arranged into these double rooms.

Input

For each data set:

The first line gives two integers, n and m(1<n<=200), indicating there are n students and m pairs of students who know each other. The next m lines give such pairs.

Proceed to the end of file.

Output

If these students cannot be divided into two groups, print "No". Otherwise, print the maximum number of pairs that can be arranged in those rooms.

Sample Input

4 4
1 2
1 3
1 4
2 3
6 5
1 2
1 3
1 4
2 5
3 6


Sample Output

No
3


题意:判断是否二分图,如果不是,输出No,如果是,输出最大匹配

代码:

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<vector>
#include<queue>
#include<stack>
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

#define MaxSize 205

int n;
int vis[MaxSize],color[MaxSize],con[MaxSize];

vector<int>stu[MaxSize];

void init()
{
for(int i=1; i<=n; i++)
{
con[i]=-1;
stu[i].clear();
}
}

bool judge(int s)//bfs染色判断是否为二分图
{
memset(color,-1,sizeof(color));
queue<int>q;

color[s]=0;
q.push(s);
while(!q.empty())
{
int t=q.front();
q.pop();
for(int i=0; i<stu[t].size(); i++)
{
int point=stu[t][i];
int stan=color[t]==1?0:1;

if(color[point]==-1)
{
color[point]=stan;
q.push(point);
}
else
{
if(color[point]!=stan)
return false;
}
}
}
return true;
}

int dfs(int x)
{
for(int i=0; i<stu[x].size(); i++)
{
int y=stu[x][i];

if(vis[y]==1) continue;

vis[y]=1;
/*if条件的判断规则是:如果满足前者条件,就直接进入if代码,不再(执行)判断后者条件。
比如这里如果con[y]==-1成立,就直接进入下面代码,不再去判断dfs(con[y])。
所以这里有个地方要特别注意:dfs(con[y])一定要写在con[y]==-1后面。因为假如con[y]==-1成立,
我们先去判断dfs(con[y]),即dfs(-1),而我们看第一步for循环那里就会爆下标导致re,所以一定一定要注意*/
if(con[y]==-1||dfs(con[y]))
{
con[y]=x;
con[x]=y;
return 1;
}
}
return 0;
}

void maxpp()//max(最大)pp(匹配)2333
{
int ans=0;
for(int i=1; i<=n; i++)
{
if(con[i]==-1)
{
memset(vis,0,sizeof(vis));
vis[i]=1;
if(dfs(i)) ans++;
}
}
printf("%d\n",ans);
}

int main()
{
int m,a,b;
while(~scanf("%d%d",&n,&m))
{
init();
while(m--)
{
scanf("%d%d",&a, &b);
stu[a].push_back(b);
stu[b].push_back(a);
}
if(!judge(1))
printf("No\n");
else
maxpp();
}
return 0;
}//FROM CJZ
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: