Bzoj 1369(树形DP)

BZOJ 1369
FJYZOJ 1432
按奇偶层染色是错误的,可以举出反例证明颜色不止2种
那么我们考虑树形DP,设$dp(i,j)​$为点$i​$染$j​$颜色时$i​$及其子树的最小权和
$$dp(i,j)=\sum_{v\in son(i)} min(dp(v,k)|k≠j)$$
然后dfs一遍求解就行了

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#define ms(i, j) memset(i, j, sizeof i)
#define LL long long
#define db double
using namespace std;
const int MAXN = 10000 + 5, INF = 1000000000;
int n, dp[MAXN][11];
vector<int> G[MAXN];
void dfs(int u, int pa) {
for (int i=1;i<=10;i++) dp[u][i] = i;
for (int i=0;i<G[u].size();i++) {
int v = G[u][i];
if (v != pa) dfs(v, u);
}
for (int j=1;j<=10;j++) {
if (G[u].size() == 1) return ;
for (int i=0;i<G[u].size();i++) {
int mini = INF;
int v = G[u][i];
if (v == pa) continue;
for (int k=1;k<=10;k++) {
if (j == k) continue;
mini = min(mini, dp[v][k]);
}
dp[u][j] += mini;
}
}
}
void clean() {
for (int i=0;i<=n;i++) {
G[i].clear();
}
}
void solve() {
clean();
for (int i=1;i<n;i++) {
int a, b;
scanf("%d%d", &a, &b);
G[a].push_back(b), G[b].push_back(a);
}
dfs(1, 0);
int ans = INF;
for (int i=1;i<=10;i++) {
ans = min(ans, dp[1][i]);
}
printf("%d\n", ans);
}
int main() {
#ifndef ONLINE_JUDGE
freopen("1.in", "r", stdin); freopen("1.out", "w", stdout);
#endif
scanf("%d", &n), solve();
fclose(stdin); fclose(stdout);
return 0;
}
------ 本文结束 ------