【二分图】 判断是否是二分图

一次比赛的题,以前都是匈牙利算法处理二分图问题(即已知是二分图),这次是判断二分图,注意处理方式的选择。

Mediacy

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 103    Accepted Submission(s): 18

 

Problem Description

In yrleep`s class,there are only two kinds of relationship between the classmates which can not be  passed,namely incompatible and live in harmony.So yrleep wants to put them into two parts to  make both of them get along well with each other in each part . Can his ideas be implemented?

 

Input

The input consists of multiple test cases.the first line input two integers n,m,n indicates the number of people

The next m lines,each line has two integers a,b,indicates a and b are incompatible.

 

Output

If his idea can come true ,output yes.if not,output no.

 

 

Sample Input

 

5 3

1 2

3 4

4 5

 

Sample Output

yes

 

 

#include <cstdio>
#include <iostream>
#include <memory.h>
#include <vector>
using namespace std;
const int maxn = 10000 + 10;
vector G[maxn];
int n, m;
int color[maxn];
bool dfs(int v, int c)
{

    color[v] = c;
    for(int i=0; i< G[v].size(); i++) {
        //如果相邻的顶点同色,则返回false
        if(color[G[v][i]] == c) return false;
        //如果相邻的顶点还没有被染色,则染成-c
        if(color[G[v][i]] == 0 && !dfs(G[v][i], -c)) return false;
    }
    return true;
}

void solve()
{
    for(int i=0; i
        if(color[i] == 0) {
            if(!dfs(i,1)) {
                printf("no\n");
                return ;
            }
        }
    }
    printf("yes\n");
}


int main()
{
//    freopen("in.txt","r",stdin);
    int i, x, y;
    while(~scanf("%d%d",&n,&m)) {
        memset(color, 0, sizeof (color) );
        for(i=1; i<=n; ++i) G[i].clear();
        for(i=1; i<=m; ++i) {
            scanf("%d%d",&x,&y);
            G[x].push_back(y);
            G[y].push_back(x);
        }
        solve();
    }
    return 0;
}

  

转载于:https://www.cnblogs.com/balfish/p/4014409.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值