Educational Codeforces Round 72 (Rated for Div. 2) D. Coloring Edges

https://codeforc.es/contest/1217/problem/D

You are given a directed graph with n vertices and m directed edges without self-loops or multiple edges.

Let’s denote the k-coloring of a digraph as following: you color each edge in one of k colors. The k-coloring is good if and only if there no cycle formed by edges of same color.

Find a good k-coloring of given digraph with minimum possible k.

Input
The first line contains two integers n and m (2≤n≤5000, 1≤m≤5000) — the number of vertices and edges in the digraph, respectively.

Next m lines contain description of edges — one per line. Each edge is a pair of integers u and v (1≤u,v≤n, u≠v) — there is directed edge from u to v in the graph.

It is guaranteed that each ordered pair (u,v) appears in the list of edges at most once.

Output
In the first line print single integer k — the number of used colors in a good k-coloring of given graph.

In the second line print m integers c1,c2,…,cm (1≤ci≤k), where ci is a color of the i-th edge (in order as they are given in the input).

If there are multiple answers print any of them (you still have to minimize k).

题意:给你个有向图,给所有边染色,使得没有一个环包含的边只有一种颜色,输出最小颜色数及染色方案。

对于有向图的环,有这样的性质:一定同时存在编号小的点指向编号大的点和编号大的点指向编号小的点的边,因此,我们把所有小指大的边染为1,大指小的边染为2,就能保证图中不存在同色环。那么问题就演变成了判断图中是否有环,这个就随便搞搞,拓扑排序啊dfs啊都可以。

代码:

#include
#include
#include
#include
#include
#include
#include
//#include
using namespace std;
#define PB push_back
#define LL long long
#define FI first
#define SE second
#define POP pop_back()
#define PII pair
#define endl '\n'
#define ls x<<1
#define rs x<<1|1
#define m(x) a[x].l+a[x].r>>1
#define ST cin>>n;for(int i=1;i<=n;i++)scanf("%d",&a[i]);
#define debug cout<<"FUCK"<
const int N=5007,mod=998244353;
int n,m;
PII a[N];
vector<int>v[N];
bool f[N];
int d[N];
int main()
{
    cin>>n>>m;
    int flag=0;
    for(int i=1;i<=m;i++){
        scanf("%d%d",&a[i].FI,&a[i].SE);
        v[a[i].FI].PB(a[i].SE);
        d[a[i].SE]++;
    }
    for(int i=1;i<=n;i++){//拓扑排序求环
        int mn=0;
        for(int j=1;j<=n;j++){
            if(d[j]==0&&f[j]==0)mn=j;
        }
        f[mn]=1;
        if(mn==0){
            flag=1;break;
        }
        for(int j=0;j<v[mn].size();j++){
            d[v[mn][j]]--;
        }
    }
    if(flag==0){
        cout<<1<<endl;
        for(int i=1;i<=m;i++){
            printf("1 ");
        }
    }
    else{
        cout<<2<<endl;
        for(int i=1;i<=m;i++){
            if(a[i].FI<a[i].SE)printf("1 ");
            else printf("2 ");
        }
    }
	return 0;
}
/*
*/

你可能感兴趣的:(Educational Codeforces Round 72 (Rated for Div. 2) D. Coloring Edges)