二分图判定
2016-05-08 17:15
295 查看
输入:V个顶点,E条边(无向)
输出:是不是二分图
example input :
3 3
0 1
1 2
0 2
给图上每个顶点着色,相邻顶点颜色不同
1、图的存储,使用vector数组
G[s].push_back(t);
G[t].push_back(s);2、图的遍历,DFS,从一点出发,遍历该点所有的相邻点
for(int j = 0 ; j < G[i].size();j++)//G[i][j]就是i的所有相邻点3、着色判断
if(v[G[i][j]]==color)return false;//如果已经着色错误
if(v[G[i][j]]==0)//如果还没有着色
{
if(!dfs(G[i][j],-color))//那么给该点的所有相邻点着色
return false;
}
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<vector>
using namespace std;
vector<int>G[1000005];
int v[10005];
bool dfs(int i,int color)
{
v[i] = color;
for(int j = 0 ; j < G[i].size();j++)
{
if(v[G[i][j]]==color)return false;
if(v[G[i][j]]==0)
{
if(!dfs(G[i][j],-color))
return false;
}
}
return true;
}
int main()
{
int V,E;
scanf("%d %d",&V,&E);
for(int i = 0 ; i < E;i++)
{
int s,t;
scanf("%d %d",&s,&t);
G[s].push_back(t);
G[t].push_back(s);
}
int flag = 0;
int color = 1;
for(int i = 0 ; i < V;i++)
{
if(v[i]==0)
{
flag = dfs(i,color);
color = (color==-1)?1:-1;
}
if(flag == 0)
break;
}
if(flag == 0)
cout<<"No"<<endl;
else
cout<<"Yes"<<endl;
}
输出:是不是二分图
example input :
3 3
0 1
1 2
0 2
〇--------① \ / \ / ②
给图上每个顶点着色,相邻顶点颜色不同
1、图的存储,使用vector数组
G[s].push_back(t);
G[t].push_back(s);2、图的遍历,DFS,从一点出发,遍历该点所有的相邻点
for(int j = 0 ; j < G[i].size();j++)//G[i][j]就是i的所有相邻点3、着色判断
if(v[G[i][j]]==color)return false;//如果已经着色错误
if(v[G[i][j]]==0)//如果还没有着色
{
if(!dfs(G[i][j],-color))//那么给该点的所有相邻点着色
return false;
}
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<vector>
using namespace std;
vector<int>G[1000005];
int v[10005];
bool dfs(int i,int color)
{
v[i] = color;
for(int j = 0 ; j < G[i].size();j++)
{
if(v[G[i][j]]==color)return false;
if(v[G[i][j]]==0)
{
if(!dfs(G[i][j],-color))
return false;
}
}
return true;
}
int main()
{
int V,E;
scanf("%d %d",&V,&E);
for(int i = 0 ; i < E;i++)
{
int s,t;
scanf("%d %d",&s,&t);
G[s].push_back(t);
G[t].push_back(s);
}
int flag = 0;
int color = 1;
for(int i = 0 ; i < V;i++)
{
if(v[i]==0)
{
flag = dfs(i,color);
color = (color==-1)?1:-1;
}
if(flag == 0)
break;
}
if(flag == 0)
cout<<"No"<<endl;
else
cout<<"Yes"<<endl;
}
相关文章推荐
- 面向对象中关于继承的调用
- The application of the static
- C++实现字符串类型(String16/String8/const char/char)转换
- 我眼中的结构体
- 绑定服务学习
- Error getting nested result map values for 'user_inf'. Cause: java.sql.SQLException: Cannot convert
- 【Android安全】使用dex2jar查看apk源码
- string - 数字反转升级版
- 生日蛋糕(DFS)
- <html>URL相关
- 2.SGI STL第二级空间配置器__default_alloc_template的chunk_alloc函数
- python的strip()内置函数,各种string内置函数见link
- Java类和对象
- The address of IP
- logic:iterate标签
- C经典 DEBUG控制Log
- 将html转为jade的工具
- 贝叶斯之起因(概率论分析)
- 【BZOJ-1097】旅游景点atr SPFA + 状压DP
- nyoj 79 导弹拦截