CF BUDDY
← Problems·

1187E · Tree Painting

2100 · dfs and similar, dp, trees

Problem: 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 Format: The first line contains an integer nn — the number of vertices in the tree (2n21052 \le n \le 2 \cdot 10^5).

Each of the next n1n - 1 lines describes an edge of the tree. Edge ii is denoted by two integers uiu_i and viv_i, the indices of vertices it connects (1ui,vin1 \le u_i, v_i \le n, uiviu_i \ne v_i).

It is guaranteed that the given edges form a tree.

Output Format: Print one integer — the maximum number of points you gain if you will play optimally.

Note: The first example tree is shown in the problem statement.

Sample Cases

Case 1

Input

9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8

Output

36

Case 2

Input

5
1 2
1 3
2 4
2 5

Output

14

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback