Codeforces Round #550 (Div. 3) F. Graph Without Long Directed Paths

F. Graph Without Long Directed Paths

题目链接:https://codeforces.com/contest/1144/problem/F

题意:

给出一个无向图,现在要求你给边定向,使得这个图中任意一条路径的长度都不超过1,最后输出一种方法即可。

题解:

易知出现奇环时最后不满足条件,所以可以联想到黑白染色来判断可行性。最后直接根据染色来确定方向即可。

代码如下:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5 + 5;
int n,m;
struct Edge{
    int u,v,next,t;
}e[N];
int head[N];
int tot;
void adde(int u,int v){
    e[tot].t=(tot + 1);e[tot].v=v;e[tot].next=head[u];head[u]=tot++;
}
vector <int> g[N];
int c[N],ans[N],vis[N];
int f;
void dfs(int u,int fa,int col){
    c[u] = col ;
    if(f) return ;
    for(auto v : g[u]) {
        if(c[v]==0) dfs(v,u,3-col);
        else if(c[v]==col) {
            f = 1;
            return ;
        }
    }
}
int main(){
    ios::sync_with_stdio(false);cin.tie(0);
    cin >> n >> m;
    memset(head,-1,sizeof(head));
    for(int i = 1; i <= m; i++){
        int u, v;
        cin >> u >> v;
        adde(u, v);
        g[u].push_back(v);
        g[v].push_back(u);
    }
    dfs(1,-1,1);
    if(f) cout << "NO";
    else {
        cout << "YES" << '\n';
        for(int i = 1;i <= n; i++) {
            for(int j = head[i]; j!=-1; j=e[j].next){
                int p = e[j].t;
                if(c[i]==1) ans[p] = 1;
            }
        }
        for(int i = 1;i <= m ; i++) {
            cout << ans[i];
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/heyuhhh/p/10679472.html