D. Coloring Edges
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
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
input
Copy
4 5 1 2 1 3 3 4 2 4 1 4
output
Copy
1 1 1 1 1 1
input
Copy
3 3 1 2 2 3 3 1
output
Copy
2 1 1 2
題意:
一張有向圖,每條邊染色,要使得每個環都不能全部爲同一種顏色,輸出最少需要的顏色和每條邊的顏色?
分析:
對於有向圖來說,一個環一定包含小號到大號的邊和大號到小號的邊,所以最多就兩種顏色,一看代碼就什麼都明白了。
#include<bits/stdc++.h>
#define LL long long
using namespace std;
const int MAXN=50100;
LL n,m,vis[MAXN],in[MAXN],a[MAXN],b[MAXN];
vector<LL> G[MAXN];
int top_sort()
{
int cnt=0;
queue<int> q;
for(int i=1; i<=n; i++)
if(!in[i])
q.push(i);
while(!q.empty())
{
int u=q.front();
cnt++;
q.pop();
for(int i=0; i<G[u].size(); i++)
if(--in[G[u][i]]==0)
q.push(G[u][i]);
}
return (n==cnt);
}
signed main()
{
cin>>n>>m;
for(int i=1; i<=m; i++)
{
cin>>a[i]>>b[i];
G[a[i]].push_back(b[i]);
in[b[i]]++;
}
if(top_sort())
{
printf("1\n");
for(int i=1; i<=m; i++)
printf("1 ");
cout<<endl;
return 0;
}
printf("2\n");
for(int i=1; i<=m; i++)
{
if(a[i]>b[i])
printf("1 ");
else
printf("2 ");
}
cout<<endl;
return 0;
}