Coloring Edges CodeForces - 1217D
You are given a directed graph with nn vertices and mm directed edges without self-loops or multiple edges.
Let's denote the kk-coloring of a digraph as following: you color each edge in one of kk colors. The kk-coloring is good if and only if there no cycle formed by edges of same color.
Find a good kk-coloring of given digraph with minimum possible kk.
Input
The first line contains two integers nn and mm (2≤n≤50002≤n≤5000, 1≤m≤50001≤m≤5000) — the number of vertices and edges in the digraph, respectively.
Next mm lines contain description of edges — one per line. Each edge is a pair of integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) — there is directed edge from uu to vv in the graph.
It is guaranteed that each ordered pair (u,v)(u,v) appears in the list of edges at most once.
Output
In the first line print single integer kk — the number of used colors in a good kk-coloring of given graph.
In the second line print mm integers c1,c2,…,cmc1,c2,…,cm (1≤ci≤k1≤ci≤k), where cici is a color of the ii-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 kk).
Examples
4 5 1 2 1 3 3 4 2 4 1 4
1 1 1 1 1 1
3 3 1 2 2 3 3 1
2 1 1 2
#include<bits/stdc++.h>//网上大佬的代码 using namespace std; typedef long long ll; const int maxn = 5e3+5; const int inf = 0x3f3f3f3f; int n, m, d[maxn], res[maxn]; vector<int> g[maxn]; struct node { int u, v; node(int u = 0, int v = 0) : u(u), v(v) {}//初始化; }edge[maxn]; int topo()//拓扑排序 { int cnt = 0; queue<int> q; for (int i = 1; i <= n; i++) if (d[i] == 0) q.push(i); //将入度为零的点放入队列 while (!q.empty()) { int t = q.front(); q.pop(); cnt++; //计算入度可以为零的点的数量 , //如果有入度不能为零的点,表明有环; for (int i = 0; i < g[t].size(); i++) { int v = g[t][i]; d[v]--; if (d[v] == 0) q.push(v); } } if (cnt == n) return 1; return 0; } int main() { cin >> n >> m; memset(d, 0, sizeof(d)); for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; if (u > v) res[i] = 2; else res[i] = 1; //使环内的边为不同颜色; g[u].push_back(v);//记录u指向v; d[v]++;//入度的数量; } if (topo()) { cout << 1 << "\n"; for (int i = 0; i < m; i++) printf("1 "); cout << "\n"; } else { cout << 2 << "\n"; for (int i = 0; i < m; i++) printf("%d ", res[i]); cout << "\n"; } return 0; }