This is an investigation of the topic of "and check set"
And check the set only and and look at both of these operations
It is worth noting that because the check operation is O (height), so we can rely on a few tricks to reduce the height of the tree, and do not increase the complexity of time
#include <iostream>using namespacestd;BOOLCheckintXinty);voidConnectintXinty);intFatherintx);int*A;intMain () {intN CIN >>N; A= (int*)malloc((n +1)*sizeof(int)); for(inti =1; I <= N; i++) {A[i]=i; } Char Get; intx, y; while(cin>>Get,Get!='S'){ if(Get=='C') {cin>> x >>y; if(check (x, y) = =true) {cout<<"Yes"<<Endl; } Else{cout<<"No"<<Endl; } } Else if(Get=='I') {cin>> x >>y; Connect (x, y); } } intCount =0; for(inti =1; I <= N; i++){ if(A[i] = =i) {Count++; } } if(Count = =1) {cout<<"The network is connected."<<Endl; } Else{cout<<"there is"<< Count <<"Components ."<<Endl; } CIN>>N;}BOOLCheckintXinty) { if(father (x) = =father (y)) { return true; } Else{ return false; }}voidConnectintXinty) { intFX = Father (x), FY =father (y); if(FX! =FY) {A[fy]=FX; } return;}intFatherintx) { if(A[x] = =x) { returnx; } returnA[X] =father (A[x]); This is the ingenious place, if X is deep in the tree, this operation makes it directly connected to the Father node, saving a lot of time}
File Transfer (25)