• 题解【洛谷P5765】[CQOI2005]珠宝


    题面

    考虑树形 DP。

    (dp_{i,j}) 表示节点 (i) 染成颜色 (j)(i) 子树内最小的编号总和。

    容易得出转移方程:(dp_{i,j}=j+sumlimits_{vin son_i, k ot =j}dp_{v,k})

    由四色定理可知,(j) 最大为 (4),因此数组大小开到 (5) 即可。

    #include <bits/stdc++.h>
    #define DEBUG fprintf(stderr, "Passing [%s] line %d
    ", __FUNCTION__, __LINE__)
    #define File(x) freopen(x".in","r",stdin); freopen(x".out","w",stdout)
    #define DC int T = gi <int> (); while (T--)
    
    using namespace std;
    
    typedef long long LL;
    typedef pair <int, int> PII;
    typedef pair <int, PII> PIII;
    
    template <typename T>
    inline T gi()
    {
        T f = 1, x = 0; char c = getchar();
        while (c < '0' || c > '9') {if (c == '-') f = -1; c = getchar();}
        while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
        return f * x;
    }
    
    const int INF = 0x3f3f3f3f, N = 50003, M = N << 1;
    
    int n;
    int tot, head[N], ver[M], nxt[M];
    int dp[N][5];
    
    inline void add(int u, int v) {ver[++tot] = v, nxt[tot] = head[u], head[u] = tot;}
    
    void dfs(int u, int f)
    {
    	for (int i = 1; i <= 4; i+=1) dp[u][i] = i;
    	for (int i = head[u]; i; i = nxt[i])
    	{
    		int v = ver[i];
    		if (v == f) continue;
    		dfs(v, u);
    		for (int j = 1; j <= 4; j+=1)
    		{
    			int mn = INF;
    			for (int k = 1; k <= 4; k+=1)
    				if (j != k) mn = min(mn, dp[v][k]);
    			dp[u][j] += mn;
    		}
    	}
    }
    
    int main()
    {
        //File("");
        n = gi <int> ();
        for (int i = 1; i < n; i+=1)
        {
        	int u = gi <int> (), v = gi <int> ();
        	add(u, v), add(v, u);
        }
        dfs(1, 0);
        printf("%d
    ", *min_element(dp[1] + 1, dp[1] + 1 + 4));
        return 0;
    }
    
  • 相关阅读:
    Caesar cipher
    遗传算法之背包问题
    Transport scheme NOT recognized: [stomp]
    error running git
    Canvas 旋转的图片
    canvas时钟
    火箭起飞
    让图标转起来
    Tomcat启动脚本
    Task中的异常处理
  • 原文地址:https://www.cnblogs.com/xsl19/p/14404413.html
Copyright © 2020-2023  润新知