Compare basic and query sets, find the number of elements contained in the Set, and use the dictionary tree in the middle to give names that appear
View code
# Include <iostream>
# Include <algorithm>
# Include < String >
# Define Maxn 100000 + 10
Using Namespace STD;
Int F [maxn], R [maxn], n, num;
Typedef Struct Node
{
Int CNT;
Struct Node * Next [ 52 ];
} * Tree, trie;
Tree root;
Inline Int Getnum ( Char * T) // Use the dictionary tree to encode strings
{
Tree P = root, newnode;
For ( Int I = 0 ; I <strlen (t); ++ I)
{
Int U;
If (T [I]> = ' A ' & T [I] <= ' Z ' )
U = T [I]- ' A ' ;
Else U = T [I]- ' A ' + 26 ;
If (P-> next [u] = NULL)
{
Newnode = (tree) malloc ( Sizeof (Trie ));
Newnode-> CNT =- 1 ;
For ( Int J = 0 ; J < 52 ; J ++)
Newnode-> next [J] = NULL;
P-> next [u] = newnode;
P = newnode;
}
Else
P = p-> next [u];
}
If (P-> CNT =- 1 ) // This node has not appeared
P-> CNT = num ++;
Return P-> CNT;
}
Void Init ()
{
For ( Int I = 0 ; I <maxn; I ++)
{
F [I] = I;
R [I] = 1 ;
}
Root = (tree) malloc ( Sizeof (Trie ));
Root-> CNT =- 1 ;
For ( Int J = 0 ; J <52 ; J ++)
Root-> next [J] = NULL;
Num = 0 ;
}
Int Find ( Int X)
{
If (X = f [x])
Return F [x];
F [x] = find (F [x]);
Return F [x];
}
Int Union (Int X, Int Y)
{
Int A = find (X );
Int B = find (y );
If (A = B) Return R [a];
If (R [a]> r [B])
{
R [a] + = R [B];
R [B] = 0 ;
F [B] =;
Return R [a];
}
R [B] + = R [a];
R [a] = 0 ;
F [a] = B;
Return R [B];
}
Int Main ()
{
Int T, A, B;
Char S1 [ 30 ], S2 [ 30 ];
While (Scanf ( " % D " , & T )! = EOF)
{
While (T --)
{
Scanf ( " % D " , & N );
Init ();
For ( Int I = 0 ; I <n; I ++)
{
Scanf ( " % S % s " , S1, S2 );
A = getnum (S1 );
B = getnum (S2 );
Printf ( " % D \ n " , Union (a, B ));
}
}
}
Return 0 ;
}