1. 程式人生 > >[圖論][二分圖判斷]The Accomodation of Students

[圖論][二分圖判斷]The Accomodation of Students

member ali itl 回路 input The turn 匹配 previous

Problem 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
 


思路:判斷是否為二分圖:在無向圖G中,如果存在奇數回路(回路中節點個數為奇數),則不是二分圖。否則是二分圖。
         
染色法判斷回路奇偶性:把相鄰兩點染成黑白兩色,如果相鄰兩點出現顏色相同則存在奇數回路。也就是非二分圖。 AC代碼:
#include <iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

int n,m;
int Map[210][210];
int flag[210];
int used[210];
int vis[210];

bool bfs_judge(){//染色法判斷是否為二分圖
  for(int i=0;i<210;i++) flag[i]=-1;
  for(int i=1;i<=n;i++){
    if(flag[i]!=-1) continue;
    flag[i]=0;
    queue<int > q;
    q.push(i);//以還未被染過色的i點(還未被搜索過的點)為起始點展開bfs
    while(!q.empty()){
        int head=q.front();
        q.pop();
        for(int j=1;j<=n;j++){
            if(!Map[head][j]) continue;
            if(flag[j]!=-1&&flag[head]==flag[j]) return false;
            else if(flag[j]==-1){flag[j]=!flag[head]; q.push(j);}
        }
    }
  }
  return true;
}

bool match(int x){
   for(int i=1;i<=n;i++){
     if(!vis[i]&&Map[x][i]){
        vis[i]=1;
        if(!used[i]||match(used[i])){
            used[i]=x;
            return true;
        }
     }
   }
   return false;
}

int main()
{
    while(scanf("%d%d",&n,&m)!=EOF){
        memset(Map,0,sizeof(Map));
        for(int i=1;i<=m;i++){
            int a,b;
            scanf("%d%d",&a,&b);
            Map[a][b]=Map[b][a]=1;//無向圖
        }
        if(bfs_judge()==false) {printf("No\n"); continue;}
        int ans=0;
        memset(used,0,sizeof(used));
        for(int i=1;i<=n;i++){
            memset(vis,0,sizeof(vis));
            if(match(i)) ans++;
        }
        printf("%d\n",ans/2);//每一對匹配被計算了兩次
    }
    return 0;
}

[圖論][二分圖判斷]The Accomodation of Students