Network Connection

Time limit1sMemory limit128 MB

Summary
Simulate weighted union operations that always merge into the second cluster's center, and answer path-length queries to the current cluster center.
Level

Medium5 of 10

Topics
Union-find, Implementation, Array
Solved
No attempts yet

Problem

Jongbin is the chairman of a very large group that runs NN companies numbered from 11 to NN. At the start, every company has its own independent computing and communication center, so it forms a cluster by itself, and that company is the center of its own cluster.

To improve their services, Seohyun, the group's CTO, designed the following procedure for merging clusters into larger ones that can be managed from a single center:

  1. Pick a company II that is currently the center of some existing cluster AA.
  2. Pick a company JJ that belongs to a different cluster BB (so B≠AB \neq A; JJ need not be a center).
  3. Connect II and JJ with a communication line. The length of this line is ∣I−J∣ mod 1000|I - J| \bmod 1000.
  4. Clusters AA and BB merge into one new cluster, and the center of the new cluster is the center of BB.

While these merges are happening, people keep asking how far a given company currently is from the center of its cluster, measured as the total length of the lines along the path from that company to the center. Write a program that carries out the merges and answers these distance queries.

Input

The input consists of several test cases. The first line contains the number of test cases TT. Each test case begins with NN (4≤N≤200004 \le N \le 20000), the number of companies. Then several lines follow, each holding one of the two commands below:

  • E I — output the distance from company II to the center of its current cluster.
  • I I J — connect center II to company JJ (perform one merge as described above).

Each test case ends with the single letter O. In each test case the total number of commands does not exceed 200000200000, and the number of I commands is fewer than NN.

Output

For each E command, print the requested distance on its own line.

Examples2

  1. Example 1

    Input
    1
    4
    E 3
    I 3 1
    E 3
    I 1 2
    E 3
    I 2 4
    E 3
    O
    
    Expected output
    0
    2
    3
    5
    
  2. Example 2

    Input
    1
    1500
    E 1500
    I 1500 200
    E 1500
    I 200 1400
    E 1500
    E 200
    I 1400 5
    E 1500
    E 1400
    O
    
    Expected output
    0
    300
    500
    200
    895
    395