Educational Codeforces Round 72 (Rated for Div. 2)-D. Coloring Edges-拓扑排序

Educational Codeforces Round 72 (Rated for Div. 2)-D. Coloring Edges-拓扑排序


【Problem Description】

Give you a directed graph, with a minimum of color to give each edge coloring, to ensure that there is no all sides of a ring are the same color.

【Solution】

Whether there is a ring topological sorting Analyzing the figures, if the ring is not present in FIG., The edges are all the same color. Otherwise, the same ring, as long as the two colors to meet the conditions of the subject, so the total number of colors that are two, for a ring, will there are two sides : 1 node number of small apex point of the large number of nodes vertex 2, the vertex points of a large number of small node number of node vertex. So these are two different sides, different colors can be dyed.


【Code】

/*
 * @Author: Simon 
 * @Date: 2019-09-16 10:46:37 
 * @Last Modified by: Simon
 * @Last Modified time: 2019-09-16 10:54:35
 */
#include<bits/stdc++.h>
using namespace std;
typedef int Int;
#define int long long
#define INF 0x3f3f3f3f
#define maxn 5005
vector<int>ans,g[maxn];
int deg[maxn];
bool bfs(int n){ //拓扑排序判断是否有环
    queue<int>q;
    for(int i=1;i<=n;i++){
        if(deg[i]==0) q.push(i);
    }
    while(!q.empty()){
        int u=q.front();q.pop();
        for(auto v:g[u]){
            deg[v]--;
            if(deg[v]==0) q.push(v);
        }
    }
    for(int i=1;i<=n;i++) if(deg[i]) return 1;
    return 0;
}
Int main(){
#ifndef ONLINE_JUDGE
    //freopen("input.in","r",stdin);
    //freopen("output.out","w",stdout);
#endif
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n,m;cin>>n>>m;
    for(int i=1;i<=m;i++){
        int u,v;cin>>u>>v;
        g[u].push_back(v);
        if(u>v) ans.push_back(1); //根据边类型染色。
        else ans.push_back(2);
        deg[v]++;
    }
    if(bfs(n)){
        cout<<"2"<<endl;
        for(auto v:ans) cout<<v<<' ';
    }else{
        cout<<"1"<<endl;
        for(int i=1;i<=m;i++) cout<<1<<' ';
    }
    cout<<endl;
#ifndef ONLINE_JUDGE
    cout<<endl;system("pause");
#endif
    return 0;
}

Guess you like

Origin www.cnblogs.com/--Simon/p/11526394.html