您当前的位置: 首页 > 

minato_yukina

暂无认证

  • 2浏览

    0关注

    138博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

CF219D Choosing Capital for Treeland

minato_yukina 发布时间:2022-08-11 22:12:19 ,浏览量:2

在这里插入图片描述 思路:一类树形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
using namespace std;
const int maxn = 1e6+5;
const int INF = 1e9+7;
typedef long long ll;
typedef pair 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 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>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;idp[i]) mn = i;
	}
	cout            
关注
打赏
1663570241
查看更多评论
0.0452s