Title Description
As stated, there is now a disjoint-set, you need to complete the merge and query operations.
Input Format
The first line contains two integers N, M, N represents a total of M elements and operations.
Next M rows, each row containing three integers Zi, Xi, Yi
When Zi = 1, the combined set of Xi and Yi where
When Zi = 2, the output Xi and Yi are in the same set, is if the Y output; otherwise it outputs N
Output Format
As above, the operation for each of the Zi = 2, has output line, each row contains a capital letter, or Y is N
Sample input and output
4 7 2 1 2 1 1 2 2 1 2 1 3 4 2 1 4 1 2 3 2 1 4
N Y N Y
Description / Tips
Constraints of time: 1000ms, 128M
Data Scale:
For 30% of the data, N <= 10, M <= 20;
For 70% of the data, N <= 100, M <= 1000;
To 100% of the data, N <= 10000, M <= 200000.
Special attention: fa array needs to be initialized, the ancestors of every node are their own
AC codes and templates
#include <the iostream> the using namespace STD; const int NN = 1e6 + 10 ; int N, M; int FA [NN]; int Find ( int X) { // query and compression path IF (X =! FA [X] ) FA [X] = Find (FA [X]); return FA [X]; } void the Join ( int x, int y) { // combined x, y set where int FX = Find (X), FY = Find (Y); IF (! FX = FY) FA [FX] =FY; } int main () { CIN >> N >> M; for ( int I = . 1 ; I <= N; I ++) FA [I] = I; // initialize each node is its own ancestor int OP , T1, T2; the while (M-- ) { Scanf ( " % D% D% D " , & OP, & T1, & T2); IF (OP == . 1 ) { the Join (T1, T2); // merge } the else { iF (Find (T1) == Find (T2)) { // query is the same ancestor COUT << " the Y"<<endl; }else{ cout<<"N"<<endl; } } } }