This page is still under construction.

Parts of this page are still being built. What you see may change.

The Mayo Empire

Time limit1sMemory limit128 MB

Summary
Each new city joins the tree by one road with possible capital moves, and the task sums the farthest road count from the capital after every addition.
Level

Medium7 of 10

Topics
Tree, Greedy
Solved
No attempts yet

Problem

In the history of Asia there was an ancient empire called Mayo, one of the strongest countries of its time. At first the empire consisted of a single city, which was also the capital. Its people were great warriors, so they began to invade their neighbors and enlarge their lands.

Every time they defeated a neighbor, they razed all of that country's cities except the biggest one and added the surviving city to the empire. They also built a road from that city to one of their own cities, so that people could travel between every city of Mayo. If the added city was big enough, it became the new capital of Mayo.

The vulnerability of a city in Mayo is the number of roads one has to pass to travel from that city to the capital of Mayo. You are given the list of every kingdom that the people of Mayo invaded and the description of the roads they built.

We want to know the maximum vulnerability among the cities after each city was added to Mayo. To keep the output short, report v1+v2+⋯+vnv_1 + v_2 + \dots + v_n, where viv_i is the maximum vulnerability of the cities right after the ii-th city was added.

Input

The input contains several test cases.

The first line of each test case contains nn (1≤n≤100 0001 \le n \le 100\,000), the number of cities in Mayo. The cities are numbered from 11 to nn in the order they were added to Mayo, so city 11 is the first city of Mayo and its initial capital.

The ii-th of the next n−1n - 1 lines contains two integers jj and cc. It means that when city i+1i + 1 was added to Mayo, a road was built between city i+1i + 1 and city jj, which already belonged to Mayo. The number cc is non-zero if city i+1i + 1 became the new capital of Mayo at the time it joined, and zero otherwise.

The last line of the input contains a single 0.

Output

For each test case, print one line containing the sum of the maximum vulnerabilities described in the statement.

Examples1

  1. Example 1

    Input
    3
    1 1
    2 1
    3
    1 1
    2 0
    0
    
    Expected output
    3
    2