Under construction

Still being built. Things may change

Cats or Dogs

Time limit3sMemory limit512 MB

Summary
Given a tree where cats, dogs, and empty huts change over Q days, find the fewest paths to block so no cat and dog can reach each other.
Level

Hard8 of 10

Topics
Tree, Dynamic programming, Graph
Solved
No attempts yet

Problem

Your son, JOI-kun, likes to have pets. There are NN huts for a pet, numbered 1 through NN, in your house garden. There are N−1N-1 paths connecting huts in both directions, and for any two huts, it is possible to move between them along some paths. Each hut can have at most one pet.

JOI-kun wants to have cats and dogs, but he is worried that they would often fight each other. For a situation where each hut has one of three states (a cat, a dog, or no pet), the danger level of the garden is defined as the minimum number of paths that must be blocked so that no cat and no dog can meet by moving along unblocked paths.

JOI-kun makes a plan to use the garden for QQ days. Initially, no hut has a pet. The plan on each day is one of the following:

  • cat: Give a new cat to hut vv, which currently has no pet.
  • dog: Give a new dog to hut vv, which currently has no pet.
  • neighbor: Give the pet in hut vv to the neighbor (so hut vv has no pet afterward).

You, as a parent, need to check whether your son's plan is dangerous. For each day, find the danger level of the garden after that day's plan.

Input

The first line contains NN. Line i+2i+2 (for 0≤i≤N−20 \le i \le N-2) contains AiA_i and BiB_i, meaning there is a path between huts AiA_i and BiB_i. It is guaranteed that any two distinct huts are connected by some sequence of paths.

The next line contains QQ. Line N+2+jN+2+j (for 0≤j≤Q−10 \le j \le Q-1) contains TjT_j and vjv_j. The plan on day j+1j+1 is cat if Tj=1T_j=1, dog if Tj=2T_j=2, and neighbor if Tj=3T_j=3, applied to hut vjv_j.

Output

For each jj from 00 to Q−1Q-1, print on its own line the danger level after the plan on day j+1j+1.

Hint

Consider a garden with 5 huts and 4 paths, connecting hut 1 with hut 2, hut 2 with hut 3, hut 2 with hut 4, and hut 4 with hut 5.

  1. First, hut 3 gets a cat and hut 5 gets a dog. Blocking the path between hut 2 and hut 4 keeps the cat and the dog apart, so the danger level is 1.
  2. Next, hut 2 gets a new cat and hut 1 gets a new dog. Blocking the path between hut 2 and hut 4 and the path between hut 1 and hut 2 keeps them apart, so the danger level is 2.
  3. Finally, the cat in hut 2 is given to the neighbor. Only the path between hut 2 and hut 3 needs to be blocked, so the danger level is 1.

Examples2

  1. Example 1

    Input
    3
    1 2
    2 3
    4
    1 1
    1 3
    2 2
    3 2
    
    Expected output
    0
    0
    2
    0
    
  2. Example 2

    Input
    5
    1 2
    2 3
    2 4
    4 5
    5
    1 3
    2 5
    1 2
    2 1
    3 2
    
    Expected output
    0
    1
    1
    2
    1