码迷,mamicode.com
首页 > 其他好文 > 详细

图论之二分图-HihoCoder1121

时间:2018-11-17 22:19:44      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:com   idt   ret   als   sdn   ==   href   span   wro   

题目链接:https://hihocoder.com/problemset/problem/1121

技术分享图片技术分享图片技术分享图片技术分享图片

二分图的相关概念:https://blog.csdn.net/qq_36345036/article/details/76977294

代码实现:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int maxn=10005;
vector<int>G[maxn];//用G[maxn]来存图
int vis[maxn];
int N,M;
bool solve()
{
    int flag=0;
    memset(vis,-1,sizeof(vis));
    queue<int>que;
    for(int i=1;i<=N;i++){
        if(vis[i]!=-1)//如果此点已经染过色了,则跳过
            continue;
        que.push(i);//找到没被染色的点,入栈
        while(!que.empty()){
            int top=que.front();
            que.pop();
            for(int j=0;j<G[top].size();j++){
                if(vis[G[top][j]]==-1){//如果与top相邻的点还未被染色,则将它们染成相反的颜色
                    vis[G[top][j]]=!vis[top];
                    que.push(G[top][j]);//再次入栈
                }
                else if(vis[G[top][j]]==vis[top]){//如果与top相邻的点已经被染色,并且与top所染颜色相同则不符合条件
                    return false;
                }
            }
        }
    }
    return true;
}
int main()
{
    int T;scanf("%d",&T);
    while(T--){
        scanf("%d%d",&N,&M);
        for(int i=1;i<=N;i++)//由题意知,i从1开始取值
        {
            G[i].clear();
        }
        for(int i=1;i<=M;i++){
            int u,v;
            scanf("%d%d",&u,&v);
            G[u].push_back(v);
            G[v].push_back(u);//虽是无向图,但因其是染色问题,所以要存成有向图便于判断是否有重色。
        }
        if(solve())
            printf("Correct\n");
        else
            printf("Wrong\n");
    }
    return 0;
}

 

图论之二分图-HihoCoder1121

标签:com   idt   ret   als   sdn   ==   href   span   wro   

原文地址:https://www.cnblogs.com/LJHAHA/p/9975676.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!