CF219D Choosing Capital for Treeland

在这里插入图片描述
思路:一类树形dp:换根dp,思考方向是得到某个点的dp答案后,是否能用同样的父子关系来推广这个dp式子.
在这个题目中,我们思考一个已经得出答案的点,也就是知道这个点去往其他点的花费,那么推广给它的相连接的结点我们会发现相差只有一条边.
我们把图建成1,0的边权,其中0是原本的单向边,1是我们后续人为加入的反向边.我们发现在进行dp式子时,只差在了这两类边上.
更进一步的,dp[u]向dp[v]转移时,如果边权是0,证明之前没有花费从u->v,而换根后,需要从v->u
故有dp[v] = dp[u]+1.
反之,如果边权是1,之前已经花费了1单位,但现在却不需要了,有dp[v]=dp[u]-1
这就是换根dp,我们首先进行第一次dfs算出1为根时的dp值,再按上述式子进行推广.

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6+5;
const int INF = 1e9+7;
typedef long long ll;
typedef pair<int,int> pii;
#define all(a) (a).begin(), (a).end()
#define pb(a) push_back(a)
//前向星
// for(int i=head[u];i!=-1;i=nxt[i]) v = to[i]
//int nxt[maxn],head[maxn],to[maxn];// head[u],cnt 初始值是-1
//int tot = -1;
//void add(int u,int v){
//	nxt[++tot] = head[u];
//	head[u] = tot;
//	to[tot] = v;
//}
struct Edge{
	int v,w;
};
vector<Edge> G[maxn];
int res = 0;int dp[maxn];
void dfs1(int u,int fa){
	for(auto [v,w] : G[u]){
		if(v!=fa){
			res+=w;
			dfs1(v,u);
		}
	}
}
void dfs(int u,int fa){
	for(auto [v,w] : G[u]){
		if(v==fa) continue;
		if(w==0) dp[v] = dp[u]+1;
		else dp[v] = dp[u] -1;
		dfs(v,u);
	}
}
int main(){
    ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n;cin>>n;
	for(int i=1;i<=n-1;i++){
		int u,v;cin>>u>>v;
		G[u].push_back({v,0});
		G[v].push_back({u,1});
	}
	dfs1(1,0);
	dp[1] = res;
	dfs(1,0);
	int mn=1;
	for(int i=1;i<=n;i++){
		if(dp[mn]>dp[i]) mn = i;
	}
	cout<<dp[mn]<<"\n";
	for(int i=1;i<=n;i++){
		if(dp[i]==dp[mn]) cout<<i<<" ";
	}
return 0;}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

minato_yukina

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

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

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

打赏作者

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

抵扣说明:

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

余额充值