题意
现给n个点,m条有向边。给这个图涂色,要求一个环内存在两种颜色,如果无环,就一种颜色即可
分析
我们知道如果整个图无环,颜色数为1,若存在环,颜色数为2
故最大颜色数为2
剩下的就是涂色问题。我们可以dfs遍历,对于一条dfs链我们标记它,当跑到祖宗节点时,我们可以知道出现环,那么给这个边涂色为2,环上其他边涂色为1,回溯过程取消标记,因为一个点可以被多个环覆盖。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
template <typename T>
void out(T x) { cout << x << endl; }
ll fast_pow(ll a, ll b, ll p) {ll c = 1; while(b) { if(b & 1) c = c * a % p; a = a * a % p; b >>= 1;} return c;}
ll exgcd(ll a, ll b, ll &x, ll &y) { if(!b) {x = 1; y = 0; return a; } ll gcd = exgcd(b, a % b, y, x); y-= a / b * x; return gcd; }
const int N = 5000 + 5;
struct node
{
int to, next, id;
}edge[N];
int head[N], col[N], num[N], tot, nu;
bool f, mark[N];
void init()
{
memset(head, -1, sizeof(head));
memset(num, 0, sizeof(num));
memset(mark, false, sizeof(mark));
nu = tot = 0;
f = false;
}
void add(int u, int v, int id)
{
edge[tot].to = v;
edge[tot].next = head[u];
edge[tot].id = id;
head[u] = tot ++;
}
void dfs(int u)
{
num[u] = ++ nu;
mark[u] = true;
for(int i = head[u]; i != -1; i = edge[i].next)
{
int to = edge[i].to, id = edge[i].id;
if(!num[to])
{
dfs(to);
}
else if(mark[to])
{
col[id] = 2, f = true;
}
}
mark[u] = false;
}
int main()
{
ios::sync_with_stdio(false);
init();
int n, m;
cin >> n >> m;
for(int i = 1; i <= m; i ++)
{
int u, v;
cin >> u >> v;
add(u, v, i);
col[i] = 1;
}
for(int i = 1; i <= n; i ++)
{
if(!num[i])
dfs(i);
}
if(f)
cout << 2 << endl;
else
cout << 1 << endl;
for(int i = 1; i <= m; i ++)
cout << col[i] << (i != m ? " " : "\n");
}