当前位置:网站首页>二分图判定
二分图判定
2022-07-06 14:26:00 【AC__dream】
先来说一下什么是二分图,对于一个图,我们将其顶点集分为两部分A和B,从而使得任意一条边的两个顶点一个在A中一个在B中,而不会出现一条边的两个顶点全部在A中或全部在B中这种情况。
先来说一个定理:一个图是二分图当且仅当这个图中不存在奇数环,也就是不存在一个环的顶点个数是奇数个。
如果利用这个定理来判定一个图是不是二分图的话那么我们就可以使用染色的方法来进行实现,就是每一条边的两个顶点的颜色一定是不相同的,我们按照这个原则来对图进行染色,如果染色成功那么这个图就是一个二分图,否则就不是一个二分图。
给出一道例题及其代码实现:

输入样例:
4 4
1 3
1 4
2 3
2 4输出样例:
Yes代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<cmath>
using namespace std;
const int N=2e5+10;
int h[N],e[N],ne[N],color[N],idx;
//color[i]代表第i个节点的颜色
void add(int x,int y)
{
e[idx]=y;
ne[idx]=h[x];
h[x]=idx++;
}
bool dfs(int x,int c)
{
color[x]=c;
for(int i=h[x];i!=-1;i=ne[i])
{
int j=e[i];
if(color[j]!=-1)//j节点已经染过颜色
{
if(color[j]==c) return false;//一条边的两个顶点颜色相同,矛盾
}
else if(!dfs(j,c^1)) return false;//发现矛盾
}
return true;//所有节点都没有发现矛盾就返回真
}
int main()
{
int n,m;
cin>>n>>m;
memset(h,-1,sizeof h);
int u,v;
for(int i=1;i<=m;i++)
{
scanf("%d%d",&u,&v);
add(u,v);add(v,u);
}
memset(color,-1,sizeof color);//初始颜色为-1
bool flag=true;
for(int i=1;i<=n;i++)
{
if(color[i]==-1)
{
if(!dfs(i,1))//将当前点染成1号颜色
{
flag=false;//出现奇数环就直接退出
break;
}
}
}
if(flag) puts("Yes");
else puts("No");
return 0;
}边栏推荐
- Set status bar style demo
- BarcodeX(ActiveX打印控件) v5.3.0.80 免费版使用
- 数据处理技巧(7):MATLAB 读取数字字符串混杂的文本文件txt中的数据
- Problems in the process of opencv300 cmake generating project
- Qt | UDP广播通信、简单使用案例
- Maximum product of three numbers in question 628 of Li Kou
- Classic sql50 questions
- GPS从入门到放弃(十三)、接收机自主完好性监测(RAIM)
- NetXpert XG2帮您解决“布线安装与维护”难题
- Bat script learning (I)
猜你喜欢

小满网络模型&http1-http2 &浏览器缓存

基于LM317的可调直流电源

Leetcode learning records (starting from the novice village, you can't kill out of the novice Village) ---1

GPS从入门到放弃(十五)、DCB差分码偏差

GPS从入门到放弃(十七) 、对流层延时

Common sense: what is "preservation" in insurance?

嵌入式常用计算神器EXCEL,欢迎各位推荐技巧,以保持文档持续更新,为其他人提供便利

【sciter】: 基于 sciter 封装通知栏组件

Write a rotation verification code annotation gadget with aardio

2500个常用中文字符 + 130常用中英文字符
随机推荐
3DMax指定面贴图
Kohana database
C#实现水晶报表绑定数据并实现打印4-条形码
Chapter 4: talk about class loader again
HDR image reconstruction from a single exposure using deep CNNs阅读札记
GPS從入門到放弃(十三)、接收機自主完好性監測(RAIM)
About the professional ethics of programmers, let's talk about it from the way of craftsmanship and neatness
搜素专题(DFS )
Powerful domestic API management tool
414. The third largest digital buckle
LeetCode刷题(十一)——顺序刷题51至55
C # realizes crystal report binding data and printing 4-bar code
C#實現水晶報錶綁定數據並實現打印4-條形碼
China 1,4-cyclohexanedimethanol (CHDM) industry research and investment decision-making report (2022 Edition)
Leetcode learning records (starting from the novice village, you can't kill out of the novice Village) ---1
Management background --2 Classification list
Save and retrieve strings
What a new company needs to practice and pay attention to
【MySQL】Online DDL详解
HDR image reconstruction from a single exposure using deep CNN reading notes