http://codeforces.com/problemset/problem/1144/F
You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph.
You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges).
Input
The first line contains two integer numbers n and m (2≤n≤2⋅105, n−1≤m≤2⋅105) — the number of vertices and edges, respectively.
The following m lines contain edges: edge i is given as a pair of vertices ui, vi (1≤ui,vi≤n, ui≠vi). There are no multiple edges in the given graph, i. e. for each pair (ui,vi) there are no other pairs (ui,vi) and (vi,ui) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph).
Output
If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print “NO” in the first line.
Otherwise print “YES” in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of ‘0’ and ‘1’) of length m. The i-th element of this string should be ‘0’ if the i-th edge of the graph should be directed from ui to vi, and ‘1’ otherwise. Edges are numbered in the order they are given in the input.
Example
Input
6 5
1 5
2 1
1 4
3 1
6 1
Output
YES
10100
给一个无向图方向使之没有第二条以上的路,也就是说每个点只能出度或者只能入度,用一个kind数组来记录每个点的种类,0表示还没有给定;
一开始假设1号点只能入度,dfs遍历,相邻的点一定是不同种的,dfs一边确定点的种类一边找是否有冲突。
#include<stdio.h>
#include<queue>
#include<string.h>
#include<vector>
using namespace std;
vector<int> edge[200005];
int n,m,kind[200005],a,b,w[200005][2];
int flag;
void dfs(int x)
{
for(int i=0;i<edge[x].size();i++)
{
int k=edge[x][i];
if(kind[k]==0)
{
kind[k]=kind[x]%2+1;
dfs(k);
}
else if(kind[k]==kind[x])
flag=1;
if(flag)return;
}
}
int main()
{
scanf("%d%d",&n,&m);
memset(kind,0,sizeof(kind));
for(int i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
w[i][0]=a;
w[i][1]=b;
edge[a].push_back(b);
edge[b].push_back(a);
}
kind[1]=1;
flag=0;
dfs(1);
if(flag)
{
printf("NO\n");
return 0;
}
printf("YES\n");
for(int i=0;i<m;i++)
{
if(kind[w[i][0]]>kind[w[i][1]])
printf("0");
else
printf("1");
}
printf("\n");
}
445

被折叠的 条评论
为什么被折叠?



