跳到正文

题解

换根DP复习记录

K77_约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年7月26日
收录
2026年8月20日
更新
2026年8月20日
篇幅
约 5 分钟
题目
P3478

版本

  1. v1当前

换根DP?

因为忘记了换根DP 写了一个和换根DP差不多的东西

[P3478 POI 2008] STA-Station - 洛谷

这是我的奇怪版

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
const ll maxn=2e6+5;
const ll mod=998244353; 
const ll lmt=1e9;
const ll INF=1e9;
vector<ll> e[maxn];
ll n;
ll fa[maxn],w[maxn];
ll down[maxn]; //到自己子树内的点
ll sz[maxn]; //子数大小
ll bro[maxn]; //和兄弟子树的点
ll up[maxn]; //和爷爷以外的点
inline int read()
{
    int x=0;char ch=getchar();
    while(!isdigit(ch)) ch=getchar();
    while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
    return x;
}
void dfs1(int now,int lst) {
	down[now]=0;
	sz[now]=1;
	for (int nxt:e[now]) {
		if (nxt==lst) continue;
		dfs1(nxt,now);
		sz[now]+=sz[nxt];
		down[now]+=down[nxt]+sz[nxt];
	}
}
void dfs2(int now,int lst) {
	for (int nxt:e[now]) {
		if (nxt==lst) continue;
		bro[nxt]=down[now]-(down[nxt]+sz[nxt])+(sz[now]-1-sz[nxt]);
		up[nxt]=bro[now]+up[now]+(n-sz[now])+1;
		dfs2(nxt,now);
	}
}

void solve() {
    n=read(); 
    for (ll i=1;i<n;i++) {
    	ll u,v;u=read(),v=read();
		e[u].push_back(v);
		e[v].push_back(u);
	}
	dfs1(1,0);
	dfs2(1,0);
	ll id=0,mx=-1;
	for (int i=1;i<=n;i++) {
		if (up[i]+bro[i]+down[i]+1>mx) id=i,mx=up[i]+bro[i]+down[i]+1;
	}
	cout<<id;
}

int main() {
    int t=1;
    int op;
    while (t--) solve();
}

正常版

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
const ll maxn=2e6+5;
const ll mod=998244353; 
const ll lmt=1e9;
const ll INF=1e9;
vector<ll> e[maxn];
ll n;
ll dp[maxn];
ll sz[maxn],dep[maxn];
inline int read()
{
    int x=0;char ch=getchar();
    while(!isdigit(ch)) ch=getchar();
    while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
    return x;
}
void dfs1(int now,int lst) {
	dep[now]=dep[lst]+1;
	sz[now]=1;
	for (int nxt:e[now]) {
		if (nxt==lst) continue;
		dfs1(nxt,now);
		sz[now]+=sz[nxt];
	}
}
void dfs2(int now,int lst) {
	for (int nxt:e[now]) {
		if (nxt==lst) continue;
		dp[nxt]=dp[now]-sz[nxt]+(n-sz[nxt]);
		dfs2(nxt,now);
	}
}

void solve() {
    n=read(); 
    for (ll i=1;i<n;i++) {
    	ll u,v;u=read(),v=read();
		e[u].push_back(v);
		e[v].push_back(u);
	}
	dfs1(1,0);
	for (int i=1;i<=n;i++) dp[1]+=dep[i];
	dfs2(1,0);
	ll id=0,mx=-1;
	for (int i=1;i<=n;i++) {
		if (dp[i]>mx) id=i,mx=dp[i];
	}
	printf("%d",id);
}

int main() {
    int t=1;
    int op;
    while (t--) solve();
}

CSP-S5-T2 午商_信奥算法题-ACGO题库

模拟赛有个换根dp 当时这个方法太复杂了 没调出来

原文