Codeforces Round #550 (Div. 3) F
题目链接
http://codeforces.com/contests
题意:
给你一个n个点m条边的无向连通图,没有自环,并且每条边只出现一次,没有重复的。
问是否存在一个方案,把无向边变成有向边,然后只存在路径为1的路,不存在路径大于等于2的路了。
如果不存在,输出no
如果存在,输出yes,并且输出这m条边的方向,如果方向与输入的方向相同,输出0,否则为1
题解
本来想的是,如果输入的无向图存在环(即n!=m+1)就输出no。后来发现这种想法不对,
比如有4个点4条边。 1->2 ,1->3, 4->2, 4->3. 这种情况也可以。
如果是环有奇数个节点就不可以,偶数个结点就可以。
这个图可以转化成染色问题,给你两种颜色,相邻两个点不能使同一种颜色。具体思路看代码注释。
代码
#include<algorithm>
#include <iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<map>
#include <cstdio>
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
int n,m;
bool flag=true;
int color[maxn];
/*
相邻两个节点,必然是一个入度为0,一个出度为0。
可以理解成图染色问题,给你两种颜色,相邻两个点颜色不能相同
color值为0表示这个点出度为0, 值为1表示这个点入度为0,
*/
int head[maxn];
int to[maxn*2];
int nex[maxn*2];
int tot=2;
void add(int x,int y){
to[tot]=y; nex[tot]=head[x];head[x]=tot++;
}
void dfs(int x,int f){
color[x]=f;
for(int i=head[x];i;i=nex[i]){
int y=to[i];
//如果相邻两个点入度都不为0,或者出度都不为0, 那么肯定存在长度为2的路径。
if(color[x]==color[y]){
flag=false;
return;
}
if(color[y]==-1){
dfs(y,!f);
}
}
}
int main(){
cin>>n>>m;
for(int i=0;i<m;i++){
int a,b;
scanf("%d%d",&a,&b);
add(a,b);
add(b,a);
}
memset(color,-1,sizeof(color));
dfs(1,0);
if(flag){
printf("YES\n");
for(int i=1;i<=m;i++){
int y=to[i*2];
//第i条边的终点的color值为1,表示这个点入度为零,只有出度。那么这条边的方向与输入的方向相反。
if(color[y]) printf("1");
else printf("0");
}
}else{
printf("NO\n");
}
return 0;
}