Problem Description Problem Analysis We need the maximum number of elements in a set
Here we can use the ran array to store the height of the tree
(see Union-Find: preventing tree degradation for details)
The maximum height can be recorded while merging
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include<stdio.h>
int par [ 10000020 ], ran [ 10000020 ];
int res ;
int find ( int m ) {
if ( m == par [ m ])
return m ;
else
return par [ m ] = find ( par [ m ]);
}
void unite ( int x , int y ) {
x = find ( x );
y = find ( y );
if ( x == y )
return ;
else {
if ( ran [ x ] < ran [ y ]) {
par [ x ] = y ;
ran [ y ] += ran [ x ];
if ( ran [ y ] > res )
res = ran [ y ];
} else {
par [ y ] = x ;
ran [ x ] += ran [ y ];
if ( ran [ x ] > res )
res = ran [ x ];
}
}
}
int main () {
int n ;
while ( scanf ( "%d" , & n ) != EOF ) {
for ( int i = 1 ; i <= 10000000 ; i ++ ) {
ran [ i ] = 1 ;
par [ i ] = i ;
}
res = 1 ;
for ( int i = 0 ; i < n ; i ++ ) {
int a , b ;
scanf ( "%d %d" , & a , & b );
unite ( a , b );
}
printf ( "%d \n " , res );
}
return 0 ;
}
This post is licensed under CC BY-NC-SA 4.0 . If it helped, or if you have anything to say, the comment box below is open. Page views
—
Unique visitors
—