二分图染色

题目链接:https://cn.vjudge.net/contest/68127#problem/B

#include<iostream>
#include<string>
#include<queue>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
# define maxn 200+10
# define inf 0x3f3f3f3f
int n,m;
int a[maxn];
int vis[maxn];
vector<int >wakaka[maxn];
queue<int >q;
void match()
{
    while(!q.empty())q.pop();
    memset(vis,0,sizeof(vis));
    q.push(1);
    while(!q.empty())
    {
        int top=q.front();
        vis[top]=1;
        q.pop();
        int len=wakaka[top].size();
        for(int i=0; i<len; i++)
        {
            int temp=wakaka[top][i];
            if(vis[temp])continue;
            a[temp]=-a[top];
            q.push(temp);
        }
    }
}
int main()
{
    while(cin>>n>>m)
    {
        for(int i=1; i<=n; i++)
        {
            wakaka[i].clear();
        }
        int flag=0;
        memset(a,0,sizeof(a));//首先给所有点都设置为0,如果不是朋友关系,则变成1和-1
        for(int i=1; i<=m; i++)
        {
            int u,v;
            cin>>u>>v;
            wakaka[u].push_back(v);
            wakaka[v].push_back(u);
            if(a[u]&&a[v]&&a[u]==a[v])//如果之前已经确定u和v是非朋友关系,结果又变成了朋友关系,这样就矛盾了,所以建图失败
            {
                flag=1;
            }
            if(a[u]==0)a[u]=1;
            a[v]=-a[u];
        }
        if(flag==1)cout<<"No"<<endl;
        else
        {
            match();
            int num1=0,num2=0;
            for(int i=1; i<=n; i++)
            {
                if(a[i]==1)num1++;
                if(a[i]==-1)num2++;
            }
            cout<<min(num1,num2)<<endl;
        }
    }
    return 0;
}

 

posted @ 2018-08-24 10:45  Let_Life_Stop  阅读(129)  评论(0编辑  收藏  举报