「Bzoj 1369」「Baltic2003」Gem (树形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一遍求解就行了

#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;
}
------ 本文结束 ------