D. Weight the Tree 树形dp好题 Codeforces Round #774 (Div. 2)

https://codeforces.com/contest/1646/problem/D
Codeforces Round #774 (Div. 2) D
定义一个点为good为它的权和等于其他相邻的点的和.计算出一个树最多有多少个好点,并且统计出该条件最少的权和.
思路:观察后发现只有两个点,一条边的情况下才有可能有两个good的点相邻,否则他们总是不相邻的.问题转化为求这个树的最大独立集.用 d p ( u , b ) dp(u,b) dp(u,b)表示u是否在集合中,b=0,代表不是,b=1代表是.
如果u在集合中,那么v一定不在.反之,u不在集合中,v可以再可以不在,两者取max即可.
最后,根据树形dp的思想,用树型结果在把结果还原即可.

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5+5;
const int INF = 1e9+7;
typedef pair<int,int> pii;
vector<int> G[maxn];
pii dp[maxn][2];// first = num of good , second = sum of node
pii dfs(int u,int b,int fa){
	pii & res = dp[u][b];
	if(res.first>=0) return res;
	res = {b,b ? (-G[u].size()):-1};
	for(auto v : G[u]){
		if(v==fa) continue;
		pii next = dfs(v,0,u);
		if(b==0) next = max(next,dfs(v,1,u));
		res.first += next.first;
		res.second += next.second;
	}
	return res;
}
vector<bool> good;
void build(pii val,int u,int fa){
	if(val==dfs(u,0,fa)){
		good[u] = false;
		for(auto v : G[u]){
			if(v==fa) continue;
			build(max(dfs(v,0,u),dfs(v,1,u)),v,u);
		}
	}
	else {
		good[u] = true;
		for(auto v : G[u]){
			if(v==fa) continue;
			build(dfs(v,0,u),v,u);
		}
	} 
}
int main(){
//    freopen("1.txt","r",stdin);
    ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n;cin>>n;
	for(int i=0;i<=n;i++){
		dp[i][0] = dp[i][1] = {-1,-1};
	}
	good.resize(n+1);
	for(int i=1;i<=n-1;i++){
		int u,v;
		cin>>u>>v;
		G[u].push_back(v);
		G[v].push_back(u);
	}
	if(n==2){
		cout<<"2 2\n1 1\n";
		return 0;
	}
	pii val = max(dfs(1,0,0),dfs(1,1,0));
	cout<<val.first<<" "<<-val.second<<"\n";
	build(val,1,0);
	for(int i=1;i<=n;i++){
		if(good[i]) cout<<G[i].size()<<" ";
		else cout<<1<<" ";
	}
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

minato_yukina

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值