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;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值