换根DP
作者:互联网
P3478
#include<bits/stdc++.h>
using namespace std;
#define f(i, a, b) for(int i = (a); i <= (b); i++)
#define cl(i, n) i.clear(),i.resize(n);
#define endl '\n'
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
const int inf = 1e9;
ll n;
vector<int> g[1000010];
ll sz[1000010], dp[1000010];
ll mx; int ans;
void dfs1(int now, int fa) {
sz[now] = 1;
f(i, 0, g[now].size() - 1) {
if(g[now][i] != fa){
dfs1(g[now][i], now); sz[now] += sz[g[now][i]];
}
}
}
void dfs2(int now, int fa) {
f(i, 0, g[now].size() - 1) {
if(g[now][i] != fa) {
dp[g[now][i]] = dp[now] + n - 2 * sz[g[now][i]];
if(dp[g[now][i]] > mx) {
mx = dp[g[now][i]]; ans = g[now][i];
}
dfs2(g[now][i], now);
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
f(i, 1, n - 1) {
int x, y; cin >> x >> y;
g[x].push_back(y); g[y].push_back(x);
}
dfs1(1, 0); f(i, 2, n) dp[1] += sz[i];
dfs2(1, 0); cout << ans << endl;
return 0;
}
标签:sz,int,ll,fa,DP,now,换根,dp 来源: https://www.cnblogs.com/Zeardoe/p/16462910.html