Dedicated ative Network
Time limit:3000 Ms |
|
Memory limit:Unknown |
|
64bit Io format:% LLD & % LlU |
[Submit] [go
Back] [Status]
Description
A very big corporation is developing its own ative network. In the beginning each of the N relational ISES of the corporation, numerated from 1 to n, organized its own computing and telecommunication center. Soon,
For amelioration of the services, the corporation started to collect some sort ISES in clusters, each of them served by a single computing and telecommunication center as follow. the corporation chose one of the existing centers I (serving the cluster)
And one of the specified ises j in some cluster B (not necessarily the center) and link them with telecommunication line. the length of the line between the specified ISES I and j is | I j | (mod 1000 ). in such a way the two old clusters are joined in a new cluster,
Served by the center of the old cluster B. unfortunately after each join the sum of the lengths of the lines linking an enterprise to its serving center cocould be changed and the end users wocould like to know what is the new length. write a program to keep Trace
Of the changes in the organization of the network that is able in each moment to answer the questions of the users.
Input
Your program has to be ready to solve more than one test case. the first line of the input file will contains only the number t of the test cases. each test will start with the number n of specified ISES (5 ≤ n ≤ 20000 ). then some number of lines (no more than 200000)
Will follow with one of the commands:
E I asking the length of the path from the enterprise I to its serving center in the moment;
I j informing that the serving center I is linked to the enterprise J.
The test case finishes with a line containing the word O. The I commands are less than N.
Output
The output shoshould contain as your lines as the number of E commands in all test cases with a single number each the asked sum of length of lines connecting the corresponding enterprise with its serving center.
Sample Input
14E 3I 3 1E 3I 1 2E 3I 2 4E 3O
Sample output
0235
#include<iostream>#include<cstring>#include<cstdio>#include<algorithm>using namespace std;#define MAXN 20010int f[MAXN];int sets[MAXN];int n;void init(){ for(int i=0;i<=n;i++) sets[i]=i,f[i]=0;}int find(int a){ if(sets[a]!=a) { int root=find(sets[a]); f[a]+=f[sets[a]]; sets[a]=root; return root; } else return a;}bool merge(int a,int b){ int x=find(a); int y=find(b); if(x==y) return false; sets[a]=y; f[a]=abs(a-b)%1000+f[b]; return true;}int main(){ int t; char s[20]; int a,b; scanf("%d",&t); while(t--) { scanf("%d",&n); init(); while(~scanf("%s",s)&&s[0]!='O') { if(s[0]=='E') { scanf("%d",&a); find(a); printf("%d\n",f[a]); } else { scanf("%d%d",&a,&b); merge(a,b); } } } return 0;}