当前位置:网站首页>二分图判定
二分图判定
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;
}
边栏推荐
- 小常识:保险中的“保全”是什么?
- 数据处理技巧(7):MATLAB 读取数字字符串混杂的文本文件txt中的数据
- zabbix 代理服务器 与 zabbix-snmp 监控
- 微信红包封面小程序源码-后台独立版-带测评积分功能源码
- Wechat red envelope cover applet source code - background independent version - source code with evaluation points function
- GPS從入門到放弃(十三)、接收機自主完好性監測(RAIM)
- 中国固态氧化物燃料电池技术进展与发展前景报告(2022版)
- i.mx6ull搭建boa服务器详解及其中遇到的一些问题
- Adjustable DC power supply based on LM317
- 十二、启动流程
猜你喜欢
墨西哥一架飞往美国的客机起飞后遭雷击 随后安全返航
Seata aggregates at, TCC, Saga and XA transaction modes to create a one-stop distributed transaction solution
2500个常用中文字符 + 130常用中英文字符
Oracle-控制文件及日志文件的管理
小常识:保险中的“保全”是什么?
每日一题:力扣:225:用队列实现栈
GPS从入门到放弃(十五)、DCB差分码偏差
Memorabilia of domestic database in June 2022 - ink Sky Wheel
Common sense: what is "preservation" in insurance?
【10点公开课】:视频质量评价基础与实践
随机推荐
Seata aggregates at, TCC, Saga and XA transaction modes to create a one-stop distributed transaction solution
Embedded common computing artifact excel, welcome to recommend skills to keep the document constantly updated and provide convenience for others
GPS从入门到放弃(十四)、电离层延时
中国VOCs催化剂行业研究与投资战略报告(2022版)
GPS从入门到放弃(十一)、差分GPS
经纪xx系统节点VIP案例介绍和深入分析异常
MariaDb数据库管理系统的学习(一)安装示意图
GNN,请你的网络层数再深一点~
GPS from getting started to giving up (XIII), receiver autonomous integrity monitoring (RAIM)
Research and investment strategy report of China's VOCs catalyst industry (2022 Edition)
搜素专题(DFS )
墨西哥一架飞往美国的客机起飞后遭雷击 随后安全返航
Solve project cross domain problems
Codeforces Round #274 (Div. 2) –A Expression
GPS从入门到放弃(十五)、DCB差分码偏差
CCNA Cisco network EIGRP protocol
GPS from getting started to giving up (XX), antenna offset
关于程序员的职业操守,从《匠艺整洁之道》谈起
Save and retrieve strings
What is the difference between animators and animators- What is the difference between an Animator and an Animation?