二分图的判定模板(dfs,bfs)
来源:互联网 发布:js获取隐藏元素的高度 编辑:程序博客网 时间:2024/05/21 14:55
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<cstring>
#define maxn 1005
#define inf 0x3f3f3f3f
using namespace std;
int n;
int first[maxn],nxt[maxn],to[maxn],e;
int color[maxn];
void add(int u,int v){
to[e]=v;
nxt[e]=first[u];
first[u]=e++;
}
bool bfs(int u,int c){
queue<int>q;
q.push(u);
color[u]=c;
while(!q.empty()){
int u=q.front();
q.pop();
for(int i=first[u];~i;i=nxt[i]){
int v=to[i];
if(color[v]==color[u])return false;
if(color[v]==0){
color[v]=-color[u];
q.push(v);
}
}
}
return true;
}
bool dfs(int u,int c)
{
color[u]=c;
for(int i=first[u];~i;i=nxt[i]){
int v=to[i];
if(color[u]==color[v])return false;
if(!color[v]){
if(!dfs(v,-c))return false;
}
}
return true;
}
int main()
{
int m;
int u,v;
freopen("in.txt","r",stdin);
while(scanf("%d%d",&n,&m)!=EOF){
memset(color,0,sizeof color);
memset(first,-1,sizeof first);
for(int i=0;i<m;i++){
scanf("%d%d",&u,&v);
add(u,v);
add(v,u);
}
if(bfs(0,1))
//if(dfs(0,1))
printf("%d\n",1);
else puts("0");
}
}
#include<algorithm>
#include<cstdio>
#include<queue>
#include<cstring>
#define maxn 1005
#define inf 0x3f3f3f3f
using namespace std;
int n;
int first[maxn],nxt[maxn],to[maxn],e;
int color[maxn];
void add(int u,int v){
to[e]=v;
nxt[e]=first[u];
first[u]=e++;
}
bool bfs(int u,int c){
queue<int>q;
q.push(u);
color[u]=c;
while(!q.empty()){
int u=q.front();
q.pop();
for(int i=first[u];~i;i=nxt[i]){
int v=to[i];
if(color[v]==color[u])return false;
if(color[v]==0){
color[v]=-color[u];
q.push(v);
}
}
}
return true;
}
bool dfs(int u,int c)
{
color[u]=c;
for(int i=first[u];~i;i=nxt[i]){
int v=to[i];
if(color[u]==color[v])return false;
if(!color[v]){
if(!dfs(v,-c))return false;
}
}
return true;
}
int main()
{
int m;
int u,v;
freopen("in.txt","r",stdin);
while(scanf("%d%d",&n,&m)!=EOF){
memset(color,0,sizeof color);
memset(first,-1,sizeof first);
for(int i=0;i<m;i++){
scanf("%d%d",&u,&v);
add(u,v);
add(v,u);
}
if(bfs(0,1))
//if(dfs(0,1))
printf("%d\n",1);
else puts("0");
}
}
0 0
- 二分图的判定模板(dfs,bfs)
- dfs,bfs的二分匹配模板(模板题hdu1150)
- 二分图判定 bfs版
- 二分图判定 DFS版
- bfs,dfs遍历图的模板
- 二分图的判定
- 二分图的判定
- 二分图的判定
- 二分图的判定
- 二分图的判定
- 二分图判定 nyoj1015(模板)
- 二分图匹配匈牙利算法(DFS, BFS两种实现模板)
- BFS/DFS 判断是否是二分图
- 二分图的判定 -- 着色
- hdu5285 二分图的判定
- 【算法】二分图的判定
- uva 11396 Claw Decomposition(二分图判定 BFS)
- 二分图之二分图的判定
- linux调试早期启动问题
- 一步一步学Remoting
- 【BZOJ 1861】 [Zjoi2006]Book 书架
- ubuntu解决QT5不能输入汉字的问题
- android 解决输入法键盘遮盖布局问题
- 二分图的判定模板(dfs,bfs)
- JPDA#3:实现代码的HotSwap
- Hibernate 的缓存机制
- mysql load data infile 解决大数据导入
- 一步一步学Remoting之二:激活模式
- ubuntu环境下MySQL修改登录密码
- Python学习笔记(三)数学函数
- zb的生日
- 一步一步学Remoting之三:复杂对象