You are given a connected undirected graph consisting of nn vertices and mm 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).
The first line contains two integer numbers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges, respectively.
The following mm lines contain edges: edge ii is given as a pair of vertices uiui, vivi (1≤ui,vi≤n1≤ui,vi≤n, ui≠viui≠vi). There are no multiple edges in the given graph, i. e. for each pair (ui,viui,vi) there are no other pairs (ui,viui,vi) and (vi,uivi,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).
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 mm. The ii-th element of this string should be '0' if the ii-th edge of the graph should be directed from uiui to vivi, and '1' otherwise. Edges are numbered in the order they are given in the input.
6 5 1 5 2 1 1 4 3 1 6 1
YES 10100
The picture corresponding to the first example:
And one of possible answers:
这个题目就是一个dfs,不是特别难,但是开始我比较蠢,我对每条边都for了一次,但是这个是一个图,所以如果我这样的话,很容易被数据把YES卡成NO
既然是一个图,那就随意找一个点进行dfs就好了,之前看了很多题解说的对每一个点进行染色(不太懂。。。)不过这个实际意思也差不多。
就是对每一个点进行标记,标记成0,1 指出去是1被指是0,然后就看代码好了
#include <cstdio> #include <algorithm> #include <cstring> #include <iostream> #include <vector> #include <queue> #define inf 0x3f3f3f3f using namespace std; typedef long long ll; const int maxn = 2e5 + 100; int vis[maxn];//1表示指出去,0表示被指 vector<int>vec[maxn]; int a[maxn], b[maxn],ok; void dfs(int s,int flag) { vis[s] = flag; int len = vec[s].size(); for(int i=0;i<len;i++) { if(vis[s]==vis[vec[s][i]]&&vis[s]>=0) { ok = 0; return; } if(vis[vec[s][i]]<0) { dfs(vec[s][i], !flag); } } } int main() { int n, m; cin >> n >> m; for(int i=1;i<=m;i++) { scanf("%d%d", &a[i], &b[i]); vec[a[i]].push_back(b[i]); vec[b[i]].push_back(a[i]); } memset(vis, -1, sizeof(vis)); ok = 1; dfs(1,1); if (!ok) printf("NO "); else { printf("YES "); for(int i=1;i<=m;i++) { if (vis[a[i]] == 0 && vis[b[i]] == 1) printf("1"); if (vis[a[i]] == 1 && vis[b[i]] == 0) printf("0"); } printf(" "); } return 0; }