E. Tree Painting
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given a tree (an undirected connected acyclic graph) consisting of nn vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:

Vertices 11 and 44 are painted black already. If you choose the vertex 22, you will gain 44 points for the connected component consisting of vertices 2,3,52,3,5 and 66. If you choose the vertex 99, you will gain 33 points for the connected component consisting of vertices 7,87,8 and 99.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer nn — the number of vertices in the tree (2≤n≤2⋅1052≤n≤2⋅105).
Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the indices of vertices it connects (1≤ui,vi≤n1≤ui,vi≤n, ui≠viui≠vi).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
input
Copy
9 1 2 2 3 2 5 2 6 1 4 4 9 9 7 9 8
output
Copy
36
input
Copy
5 1 2 1 3 2 4 2 5
output
Copy
14
Note
The first example tree is shown in the problem statement.
题意:找一个根,使得子树之和最大
思路:普通的树形DP是用一次DFS来获取DP[i] (以 i 点为根的子树大小 ),换根DP就是在此基础上 再跑一次DFS 通过推出的式子 O(1)来获取以下一个点做根的贡献
就此题来说,假设当前点的贡献是val ,则下一个点的贡献则为 val - dp[v] + ( n - dp[v] ) , 式子的意义也就是到下一个点时,会少一个以v为根的子树大小,但会多出一个以u为根的子树大小
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
typedef long long ll;
typedef long double ld;
//typedef __int128 bll;
const int maxn = 2e5 + 100;
const int mod = 1e9+7;
const ll inf = 1e18;
ll n,dp[maxn],ans;
vector<ll>G[maxn];
void dfs(ll now,ll fa,ll val)
{
for(ll i = 0; i < G[now].size(); ++i)
{
ll to = G[now][i];
if(to != fa)
{
ll tmp = val-dp[to]+(n-dp[to]);
ans = max(ans,tmp);
dfs(to,now,tmp);
}
}
return ;
}
void get(ll now,ll fa)
{
dp[now] = 1;
for(ll i = 0; i < G[now].size(); ++i)
{
ll to = G[now][i];
if(to != fa)
{
get(to,now);
dp[now] += dp[to];
}
}
ans += dp[now];
return ;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin >> n;
for(ll i = 1; i < n; i++)
{
ll u,v;
cin >> u >> v;
G[u].push_back(v);
G[v].push_back(u);
}
get(1,1);
dfs(1,1,ans);
cout << ans << endl;
return 0;
}

本文介绍了一种在树形结构上进行动态规划的方法,即树形DP,并通过换根DP技巧优化计算过程,以求解在树上寻找最佳根节点的问题,使子树之和达到最大值。文章提供了具体的实现代码和示例,展示了如何通过两次DFS算法高效地解决该问题。
555

被折叠的 条评论
为什么被折叠?



