A very big corporation is developing its corporative network. In the beginning each of the Nenterprises of the corporation, numerated from 1 to N, organized its own computing andtelecommunication center. Soon, for amelioration of the services, the corporation started to collectsome enterprises in clusters, each of them served by a single computing and telecommunicationcenter as follow. The corporation chose one of the existing centers I (serving the cluster A) andone of the enterprises J in some cluster B (not necessarily the center) and link them withtelecommunication line. The length of the line between the enterprises 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 clusterB. Unfortunately after each join the sum of the lengths of the lines linking an enterprise to its servingcenter could be changed and the end users would like to know what is the new length. Write aprogram to keep trace of the changes in the organization of the network that is able in eachmoment to answer the questions of the users.
E I � asking the length of the path from the enterprise I to its serving center in the moment;The test case finishes with a line containing the word O. The I commands are less than N.
I I J � informing that the serving center I is linked to the enterprise J.
1 4 E 3 I 3 1 E 3 I 1 2 E 3 I 2 4 E 3 O
0 2 3 5
思路:添加d[i]数组表示结点i到父节点的距离。。。
#include <cstdio> #include <algorithm> using namespace std; const int maxn = 20000 + 10; int pa[maxn], d[maxn]; int find(int x) { if(pa[x] != x){ int root = find(pa[x]); d[x] += d[pa[x]]; return pa[x] = root; }else return x; } int main() { int T; scanf("%d", &T); while(T--){ int n, u, v; char cmd[9]; scanf("%d", &n); for(int i=1; i<=n; i++){pa[i] = i; d[i] = 0;} while(scanf("%s",cmd) && cmd[0] !='O'){ if(cmd[0] == 'E'){scanf("%d", &u); find(u); printf("%d\n", d[u]);} if(cmd[0] == 'I'){scanf("%d%d", &u, &v);pa[u] = v; d[u] = abs(u-v) % 1000;} } } return 0; }