[Switch]
Resolution:Query the questions of the set and expand the set. The general idea is to initialize first, each number is a group, and then two gangs are a group, but the two given elements have three relationships: In
The same gang; In
Different gangs; Not
Sure
Yet;
The disadvantage of using this model is that it is complicated to judge the relationship between two elements, so the model needs to be improved. The correct model of this question is to make up a set of elements with determined relationships, and then use
Father is the same one to determine the relationship between the two elements. Father [a] stores the root node of A, and rank stores the relationship between Father [a] and A. 0 indicates two
Is not in the same gangs. 1 indicates that the two are in the same gangs. The specific program follows and queries the make_set (), find_set (),
Union_set.
TIPS:The following three steps are required: make_set (), find_set (), and union_set ().
The change in rank [a] is updated along with the change in Father [a] (there is a change in rank when there is a change in Father). If father changes, rank remains unchanged, at this time, rank records an incorrect value, and father does not change (even if the actual father is not the current value, as long as the father is not changed, rank
The value is "correct" and it is important to realize this .), The first error is because you have not considered this.
# Include <iostream>
# Include <cstdio>
Using namespace STD;
Int father [100000 + 10]; // represents the root node of X.
Int rank [100000 + 10];
Void make_set (int n ){
Int I;
For (I = 1; I <= N; I ++ ){
Father [I] = I;
Rank [I] = 1;
}
}
Int find_set (int ){
If (A = Father [a])
Return;
Else {
Int temp = Father [a];
Father [a] = find_set (father [a]);
Rank [a] = (rank [temp] + rank [a] + 1) % 2;
// Required. The relationship between A and the root node after the Update PATH is compressed. If father is changed, rank must be changed.
}
Return father [a];
}
Void union_set (int A, int B ){
Int FA, FB;
Fa = find_set ();
Fb = find_set (B );
If (Fa! = FB ){
Father [fa] = FB;
Rank [fa] = (rank [a] + rank [B]) % 2; // rank of the nodes below the FA node does not need to be changed
}
}
Int main (){
// Freopen ("1in.txt", "r", stdin );
// Freopen ("1out.txt", "W", stdout );
Int t, n, m;
Char ch;
Int A, B, fa, FB;
Scanf ("% d", & T );
While (t --){
Scanf ("% d", & N, & M );
Make_set (N );
Int I;
For (I = 1; I <= m; I ++ ){
Getchar ();
Scanf ("% C % d", & Ch, & A, & B );
If (CH = 'A '){
If (find_set (A) = find_set (B )){
// Before rank is used, the rank value of all nodes in path a has been changed when the find_set function is used to search for.
If (rank [a] + rank [B]) % 2 = 0 ){
Printf ("in the same gang. \ n ");
}
Else
Printf ("in different gangs. \ n ");
}
Else {
Printf ("Not sure yet. \ n ");
}
}
Else {
Union_set (A, B );
}
}
}
Return 0;
}