SuitNdtie

TASK038 Graph_Cycle

Mar 12th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. typedef struct{
  5.     int parent;
  6.     int rank;
  7. }subset;
  8.  
  9. int find(int x,subset set[]){
  10.     if(set[x].parent == x){
  11.         return x;
  12.     }
  13.     return set[x].parent = find(set[x].parent,set);
  14. }
  15.  
  16. void unions(int x,int y,subset set[]){
  17.     int rootx = find(x,set);
  18.     int rooty = find(y,set);
  19.    
  20.     if(set[rootx].rank > set[rooty].rank){ //x is higher rank
  21.         set[rooty].parent = rootx; 
  22.     }
  23.     else if(set[rootx].rank < set[rooty].rank){ //y is higher rank
  24.         set[rootx].parent = rooty;
  25.     }
  26.     else{ //rank x equal rank y
  27.         set[rootx].parent = rooty;
  28.         set[rooty].rank++;
  29.     }
  30. }
  31.  
  32. int main(){
  33.     int v,e;
  34.     cin>>v>>e;
  35.     subset set[v+1];for(int i=0;i<=v;i++){
  36.         set[i].parent = i;
  37.         set[i].rank = 0;
  38.     }
  39.     bool iscycle = false;
  40.     for(int i=0;i<e;i++){
  41.         int u,v;
  42.         cin>>u>>v;
  43.         if(find(u,set) == find(v,set)){
  44.             iscycle = true;
  45.         }else{
  46.             unions(u,v,set);
  47.         }
  48.     }
  49.     cout<<(iscycle?"Yes":"No");
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment