#P8059. [POI 2003] Monkeys

[POI 2003] Monkeys

Problem Description

There are nn monkeys on a tree. They are numbered from 11 to nn. Monkey 11 is holding onto a branch with its tail. Each of the remaining monkeys is either hooked by other monkeys or is hooking other monkeys with its hands. Each monkey can use two hands to hook other monkeys, and each hand can hook at most one monkey.

Starting from time 00, every second one monkey lets go with one of its hands. This may cause some monkeys to fall to the ground. We want to know the time when each monkey falls to the ground (the monkeys fall so fast that the falling time can be ignored).

Input Format

The first line contains two integers nn and mm. nn is the total number of monkeys, and mm is the total time we observe the monkeys.

The next nn lines describe the initial situation. The kk-th line contains two integers, which represent which two monkeys are held by the left hand and the right hand of monkey kk, respectively. 1-1 means that hand is empty.

The next mm lines describe the activities we observe. The ii-th line contains two integers, representing which monkey lets go and which hand it lets go with at time i1i - 1 (11 for left, 22 for right).

Output Format

Output nn integers, one per line, representing the time when each monkey falls to the ground. If it never falls, output -1.

3 2
-1 3
3 -1
1 2
1 2
3 1
-1
1
1

Hint

Constraints: for all testdata, 1n2×1051 \le n \le 2 \times 10^5, 1m4×1051 \le m \le 4 \times 10^5.

Translated by ChatGPT 5