【換根DP】E. Tree Painting

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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章