HDU 5285 wyh2000 and pupil(二分图,染色法)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5285


“if two pupils are in the same group,then they know each other ” at my first glance , I mistaken this sentence 's meaning,It's just a simple Bipartite Graph‘s problem;


In this question , I used a simple algorithm called  Staining  to color node in black or white , and all the nodes in black are at one group, the other group combined with nodes in white.



【代码】

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
typedef long long ll;
const int maxn = 110010;
vector <int>G[maxn];
int color[maxn];
void init(int n){
    for(int i=0;i<=n;i++)
    {
        G[i].clear(); color[i] = -1; //初始化
    }
}
bool bicolorable(int x,int& l,int& r){ //l 记录当前联通块的总结点数, r:记录color为 1的节点数
    queue<int>Q;
    color[x] = 1;
    l++;
    r++;
    Q.push(x);
    while(!Q.empty()){
        int v1 = Q.front();
        Q.pop();
        for(int i=0;i<G[v1].size();i++){
            int v2 = G[v1][i];

            if(color[v2] == -1){
                color[v2] = !color[v1];
                l++;
                if(color[v2] == 1)
                    r++;
                Q.push(v2);
            }
            else if(color[v2] == color[v1])
                return false;
        }
    }
    return true;
}
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        int n,m;
        scanf("%d%d",&n,&m);
        init(n);
        for(int i=0;i<m;i++){
            int a,b;
            scanf("%d%d",&a,&b);
            G[a].push_back(b);
            G[b].push_back(a);
        }
        if(n<=1){ //特判
            printf("Poor wyh\n");
            continue;
        }
        if(m == 0) {
            printf("%d 1\n", n - 1);
            continue;
        }
        int ac = 0; int Max=0;
        for(int i=1;i<=n;i++){
                int l= 0 ,r = 0;
            if( -1 == color[i]){
                if(!bicolorable(i,l,r)){
                    ac = 1;break;
                }
                Max += max(r,l-r); //较多的一组加入Max
            }
        }
        if(ac){
            printf("Poor wyh\n");
        }
        else{
            printf("%d %d\n",Max,n-Max);
        }
    }
    return 0;
}






你可能感兴趣的:(二分图)