Network Connection
Time limit1sMemory limit128 MB
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 companies numbered from to . 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:
- Pick a company that is currently the center of some existing cluster .
- Pick a company that belongs to a different cluster (so ; need not be a center).
- Connect and with a communication line. The length of this line is .
- Clusters and merge into one new cluster, and the center of the new cluster is the center of .
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 . Each test case begins with (), the number of companies. Then several lines follow, each holding one of the two commands below:
E I— output the distance from company to the center of its current cluster.I I J— connect center to company (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 , and the number of I commands is fewer than .
Output
For each E command, print the requested distance on its own line.