当前位置:网站首页>二分图判定
二分图判定
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;
}边栏推荐
- Spatial domain and frequency domain image compression of images
- LeetCode刷题(十一)——顺序刷题51至55
- 重磅新闻 | Softing FG-200获得中国3C防爆认证 为客户现场测试提供安全保障
- Oracle性能分析3:TKPROF简介
- [linear algebra] determinant of order 1.3 n
- 【sciter Bug篇】多行隐藏
- 2020 Bioinformatics | GraphDTA: predicting drug target binding affinity with graph neural networks
- Insert sort and Hill sort
- The nearest common ancestor of binary (search) tree ●●
- GPS從入門到放弃(十三)、接收機自主完好性監測(RAIM)
猜你喜欢

BarcodeX(ActiveX打印控件) v5.3.0.80 免费版使用

GNN,请你的网络层数再深一点~

2500个常用中文字符 + 130常用中英文字符

Leetcode question brushing (XI) -- sequential questions brushing 51 to 55

GPS from entry to abandonment (XIV), ionospheric delay

Search element topic (DFS)

PVL EDI project case

Assembly and interface technology experiment 5-8259 interrupt experiment

二叉(搜索)树的最近公共祖先 ●●

Xiaoman network model & http1-http2 & browser cache
随机推荐
[MySQL] online DDL details
设置状态栏样式Demo
中国1,4-环己烷二甲醇(CHDM)行业调研与投资决策报告(2022版)
Leetcode learning records (starting from the novice village, you can't kill out of the novice Village) ---1
Common sense: what is "preservation" in insurance?
[sciter]: encapsulate the notification bar component based on sciter
Learn the principle of database kernel from Oracle log parsing
Chapter 4: talk about class loader again
[线性代数] 1.3 n阶行列式
Unity3D学习笔记6——GPU实例化(1)
插入排序与希尔排序
Search element topic (DFS)
GPS from getting started to giving up (XI), differential GPS
3DMax指定面贴图
What a new company needs to practice and pay attention to
i. Mx6ull build boa server details and some of the problems encountered
C#實現水晶報錶綁定數據並實現打印4-條形碼
HDR image reconstruction from a single exposure using deep CNN reading notes
Assembly and interface technology experiment 5-8259 interrupt experiment
Powerful domestic API management tool