Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- typedef struct{
- int parent;
- int rank;
- }subset;
- int find(int x,subset set[]){
- if(set[x].parent == x){
- return x;
- }
- return set[x].parent = find(set[x].parent,set);
- }
- void unions(int x,int y,subset set[]){
- int rootx = find(x,set);
- int rooty = find(y,set);
- if(set[rootx].rank > set[rooty].rank){ //x is higher rank
- set[rooty].parent = rootx;
- }
- else if(set[rootx].rank < set[rooty].rank){ //y is higher rank
- set[rootx].parent = rooty;
- }
- else{ //rank x equal rank y
- set[rootx].parent = rooty;
- set[rooty].rank++;
- }
- }
- int main(){
- int v,e;
- cin>>v>>e;
- subset set[v+1];for(int i=0;i<=v;i++){
- set[i].parent = i;
- set[i].rank = 0;
- }
- bool iscycle = false;
- for(int i=0;i<e;i++){
- int u,v;
- cin>>u>>v;
- if(find(u,set) == find(v,set)){
- iscycle = true;
- }else{
- unions(u,v,set);
- }
- }
- cout<<(iscycle?"Yes":"No");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment