前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >洛谷P3177 [HAOI2015]树上染色(树上背包)

洛谷P3177 [HAOI2015]树上染色(树上背包)

作者头像
attack
发布2018-10-11 16:05:11
4690
发布2018-10-11 16:05:11
举报
文章被收录于专栏:数据结构与算法

题意

题目链接

Sol

比较套路吧,设\(f[i][j]\)表示以\(i\)为根的子树中选了\(j\)个黑点对答案的贡献

然后考虑每条边的贡献,边的两边的答案都是可以算出来的

转移的时候背包一下。

代码语言:javascript
复制
#include<bits/stdc++.h>
#define Pair pair<int, int>
#define fi first
#define se second
#define MP(x, y) make_pair(x, y)
#define LL long long 
const int MAXN = 2001, INF = 1e9 + 7;
using namespace std;
inline int read() {
    int x = 0, f = 1; 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 x * f;
}
int N, K, siz[MAXN];
LL f[MAXN][MAXN];
vector<Pair> v[MAXN];
void dfs(int x, int fa) {
    siz[x] = 1; f[x][1] = f[x][0] = 0;
    for(int i = 0; i < v[x].size(); i++) {
        int to = v[x][i].fi, w = v[x][i].se;
        if(to == fa) continue;
        dfs(to, x);
        siz[x] += siz[to];
    }
    for(int i = 0; i < v[x].size(); i++) {
        int to = v[x][i].fi, w = v[x][i].se;
        if(to == fa) continue;
        for(int j = min(siz[x], K); j >= 0; j--) 
            for(int k = 0; k <= min(siz[to], j); k++)
                if(f[x][j - k] >= 0)
                f[x][j] = max(f[x][j], f[x][j - k] + f[to][k] + 1ll * k * (K - k) * w + 1ll * (siz[to] - k) *  (N - (K - k) - siz[to]) * w);
    }
}
 main() {
    N = read(); K = read();
    for(int i = 1; i <= N - 1; i++) {
        int x = read(), y = read(), w = read();
        v[x].push_back(MP(y, w));
        v[y].push_back(MP(x, w));
    }
    memset(f, -0x7f, sizeof(f));
    dfs(1, 0);
    cout << f[1][K];
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-10-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题意
  • Sol
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档