HDU 2444 The Accomodation of Students (二分图判定+最大匹配

来源:互联网 发布:审美差异知乎 编辑:程序博客网 时间:2024/06/07 02:19

The Accomodation of Students

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

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 41 21 31 42 36 51 21 31 42 53 6

Sample Output

No3

题解:

判断这些人是否能分成两部分,每个部分的人若有互相认识的人则no,例如:1认识2和3,若2和3认识,则NO,
若分成的两部分是YES,则求出最大匹配数(认识的人才能匹配)

AC代码

#include <bits/stdc++.h>using namespace std;#define LL long long#define CLR(a,b) memset(a,(b),sizeof(a))const int INF = 0x3f3f3f3f;const int MAXN = 1e3;int color[MAXN];int G[MAXN][MAXN];int used[MAXN];int linker[MAXN];bool flag;int vN;int m;bool bfs(int s){    color[s] = 1;    queue<int> q;    q.push(s);    while(!q.empty()) {        int u = q.front();        q.pop();        for(int v = 1; v <= vN; v++) {            if(G[u][v] && color[v]==0) {                q.push(v);                color[v] = -color[u];            }            if(G[u][v] && color[v]==color[u]) return false;        }    }    return true;}void check(){    for(int v = 1; v <= vN; v++) {        if(color[v]==0 && !bfs(v)) {            flag = true; return;        }    }}bool dfs(int u){    for(int v = 1; v <= vN; v++) {        if(G[u][v] && !used[v]) {            used[v] = true;            if(linker[v]==-1 || dfs(linker[v])) {                linker[v] = u;                return true;            }        }    }return false;}int hungary(){    int res = 0;    CLR(linker,-1);    for(int i = 1; i <= vN; i++) {        CLR(used,false);        if(dfs(i)) res++;    }    return res;}int main(){    int m;    while(~scanf("%d%d",&vN,&m)) {        CLR(G,0); CLR(color,0);        for(int i = 0; i < m; i++) {            int u, v;            scanf("%d%d",&u,&v);            G[u][v] = G[v][u] = 1;        }        flag = false;        check();        if(flag) {            puts("No");        }        else {            printf("%d\n",hungary()/2);        }    }return 0;}
阅读全文
2 0
原创粉丝点击