Corporative Network UVALive - 3027(带权并查集+路径压缩)

A very big corporation is developing its corporative network. In the beginning each of the N enterprises
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 enterprises 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 A) and one of the enterprises J in some other
cluster B (not necessarily the center) and link them with telecommunication 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 cluster B. Unfortunately after each join the sum of the
lengths of the lines linking an enterprise to its serving center could be changed and the end users would
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.
Your program has to be ready to solve more than one test case.
Input
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 enterprises (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 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 should contain as many 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
1
4
E 3
I 3 1
E 3
I 1 2
E 3
I 2 4
E 3
O
Sample Output
0
2
3
5

第二次遇见带权并查集了,这次还是做出来了,虽然出了一点点问题。
题目大意:
有n个节点,当输入E x的时候询问x节点的最长联通网络距离,默认为0,当输入为I x y表示x到y的联通网络距离为(x-y)%1000,输入以‘O’结束。
思路:根据样例可以发现就是一个并的过程第一个询问3,此时3是初始值0,第二次询问3,因为I 3 1,表示3节点和1节点已经联通了,距离为(3-1)%1000=2,所以输出2,第三次询问3,因为I 1 2,节点1与节点2已经联通距离为|(1-2)|%1000=1,而3节点与1节点已经联通距离为2,2节点又与1节点联通,所以3节点也与1节点联通,3节点最大距离为2+1=3,第四次也是一样。
ac代码:

#include
#include
#define maxn 20010
using namespace std;

int dis[maxn],parent[maxn];
int find_x(int x){
	if(x!=parent[x]){
		int i=parent[x];
		parent[x]=find_x(parent[x]);
		dis[x]+=dis[i];
	}
	return parent[x];
}
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		int n,t1,t2;
		cin>>n;
		for(int i=1;i<=n;i++){
			parent[i]=i;dis[i]=0;
		}
		char ch;
		while(cin>>ch&&ch!='O')
		{
		if(ch=='E'){
			cin>>t1;
			find_x(t1);
			cout<<dis[t1]<<endl;
		}
		if(ch=='I'){
			cin>>t1>>t2;
			parent[t1]=t2;
			dis[t1]=abs(t1-t2)%1000;
		}
	    }
    }
}

你可能感兴趣的:(并查集)