给定一个具有 n 个顶点的图。
要给图上每个顶点染色,并且要使相邻的顶点颜色不同。
问是否能用最多两种颜色进行染色?题目保证没有重边和自环。
输入
- 第一行一个整数 n(1≤n≤1000),表示顶点个数
- 接下来每行有两个整数 x 和 y,表示顶点 x 和 y 之间有一条边,0≤x,y<n,x≠y
- 以
EOF(end of file)
作为边数据的结束
输出
Yes
或No
表示是否能用两个颜色进行染色
样例 1
输入
3 0 1 1 2 2 0
输出
No
#include<bits/stdc++.h>
using namespace std;
int n;
int color[1001];
vector<int>e[1001];
bool dfs(int v,int c)
{
color[v]=c;
for(int i=0;i<e[i].size();i++)
{
if(color[e[v][i]]==c)
return false;
if(color[e[v][i]]==0&&!dfs(e[v][i],-c))
return false;
}
return true;
}
int main()
{
while(cin>>n)
{
for(int i=0;i<n;i++)
{
int v1,v2;
cin>>v1>>v2;
e[v1].push_back(v2);
e[v2].push_back(v1);
}
for(int i=0;i<n;i++){
if(color[i]==0){
if(!dfs(i,1)){
cout<<"No"<<endl;
return 0;
}
}
}
cout<<"Yes"<<endl;
}
return 0;
}