PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#SRD0000123. Những chuồng bò mới (New Barns)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Những chuồng bò mới (New Barns)

New Barns

Source: USACO

Version: Phuoc Hung OJ Extended

Problem Statement

Initially, no barns exist. Process QQ operations that construct a forest of barns and ask distance queries.

  • B p: build a new barn with index equal to the number of already built barns plus one. If p=−1p=-1, the new barn starts a new connected component. Otherwise, add one bidirectional path from the new barn to the already existing barn pp.
  • Q k: find the maximum distance from barn kk to any other barn reachable from kk via the current paths. Distance is the number of edges along the path.

Every new barn connects to at most one old barn, so the graph remains a forest. Barns in different connected components do not contribute to each other's answers. An isolated barn has answer 00.

Input

  • The first line contains integer QQ.
  • The next QQ lines contain an operation B p or Q k.
  • For B p, either p=−1p=-1 or pp is an existing barn index.
  • For Q k, kk is an existing barn index; queries are guaranteed to be valid.

Output

For each Q k operation, print one line with the maximum distance from kk to a barn in the same connected component.

Subtasks

General guarantees: 1≤Q≤100 0001\le Q\le100\,000; barn indices start at 11; all operations are valid.

  • Subtask 1 (10 points): 1≤Q≤1001\le Q\le 100; all general guarantees remain in force.
  • Subtask 2 (20 points): 1≤Q≤1,5001\le Q\le 1,500; all general guarantees remain in force.
  • Subtask 3 (30 points): 1≤Q≤20,0001\le Q\le 20,000; all general guarantees remain in force.
  • Subtask 4 (40 points): 1≤Q≤100,0001\le Q\le 100,000; all general guarantees remain in force (full original constraints).

Examples

Example 1

Input

7
B -1
Q 1
B 1
B 2
Q 3
B 2
Q 2

Output

0
2
1

Explanation

After constructing isolated barn 11, Q 1 is 00. Building barns attached to 11 and then 22 produces the path 1−2−31-2-3, so the farthest barn from 33 is 11, at distance 22. After building barn 44 attached to 22, every other barn in that component is one edge away from 22, giving the final answer 11.