UVa 13038 - Directed Forest

contents

  1. 1. Problem
  2. 2. Sample Input
  3. 3. Sample Output
  4. 4. Solution

Problem

給予一張有向森林圖,要求任兩點若有一條路徑,則兩點不可著相同顏色,請問最少著色數為何?

Sample Input

1
2
3
4
5
6
7
8
9
10
11
12
3
4 2
1 2
3 4
4 3
1 2
2 3
4 1
7 3
3 6
3 7
1 5

Sample Output

1
2
3
Case 1: 2
Case 2: 4
Case 3: 2

Solution

明顯地,最長路徑長度若為 $L$,至少需要 $L$ 個顏色,因此針對每一個樹根進行最長路徑搜索即可,又由於題目給定森林,把每一個樹根抓出來取最大值即可。複雜度 $\mathcal{O}(N)$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 131072;
vector<int> g[MAXN];
int indeg[MAXN];
int dfs(int u) {
int ret = 1;
for (auto &v : g[u])
ret = max(ret, dfs(v)+1);
return ret;
}
int solve(int root, int N) {
return dfs(root);
}
int main() {
int testcase, cases = 0;
int N, M, u, v;
scanf("%d", &testcase);
while (testcase--) {
scanf("%d %d", &N, &M);
for (int i = 0; i <= N; i++)
g[i].clear(), indeg[i] = 0;
for (int i = 0; i < M; i++) {
scanf("%d %d", &u, &v);
g[u].push_back(v), indeg[v]++;
}
int ret = 1;
for (int i = 1; i <= N; i++) {
if (indeg[i] == 0)
ret = max(solve(i, N), ret);
}
printf("Case %d: %d\n", ++cases, ret);
}
return 0;
}