[樹形dp][HAOI2015]樹上染色

瑪珈山大萌新發表於2020-10-26

題目:[HAOI2015]樹上染色

分析:

dp[i][j]表示第i個點染j個黑色時的對答案的最大貢獻。
這裡我們採用“合併法”求dp,即將兩個子問題合併算大問題的答案。

程式碼:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;//三年競賽一場空,不開long long見祖宗 
//typedef __int128 lll;
#define print(i) cout << "debug: " << i << endl
#define close() ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define mem(a, b) memset(a, b, sizeof(a))
#define pb(a) push_back(a)
#define x first
#define y second
typedef pair<int, int> par;
const ll mod = 10007;
const int maxn = 2000 + 10;
const int inf = 0x3f3f3f3f;
struct edge
{
    int v, val, nex;
    edge(int v = 0, int val = 0, int nex = 0) : v(v), val(val), nex(nex){}
}e[maxn << 1];
int head[maxn], tot;
ll siz[maxn];
ll dp[maxn][maxn];
int n, k;

void init() {mem(head, -1), tot = 0;}
void addedge(int x, int y, int val)
{
    e[tot] = edge(y, val, head[x]);
    head[x] = tot++;
}

void dfs0(int u, int fa)
{
    siz[u] = 1;
    for(int i = head[u]; ~i; i = e[i].nex)
    {
        int v = e[i].v;
        if(v == fa) continue;
        dfs0(v, u);
        siz[u] += siz[v];
    }
}

void dfs(int u, int fa)
{
    siz[u] = 1;
    for(int i = head[u]; ~i; i = e[i].nex)
    {
        int v = e[i].v;
        if(v == fa) continue;
        dfs(v, u);
        for(int j = siz[u]; j >= 0; j--)
            for(int p = siz[v]; p >= 0; p--)//合併之前保證兩個子問題是沒有交集的。
            {
                ll val = (1ll * p * (k - p) + 1ll * (siz[v] - p) * (n - k - siz[v] + p)) * e[i].val;
                dp[u][j + p] = max(dp[u][j + p], dp[u][j] + dp[v][p] + val);
            }
        siz[u] += siz[v];//合併完了再更新siz
    }
    
}



int main()
{
    cin >> n >> k;
    init();
    for(int i = 1; i < n; i++)
    {
        int a, b, c; cin >> a >> b >> c;
        addedge(a, b, c), addedge(b, a, c);
    }
    //dfs0(1, -1);
    dfs(1, -1);
    cout << dp[1][k] << endl;
}

相關文章