Advertisement
Guest User

Untitled

a guest
Jun 19th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. struct list{
  2.   int u, v;
  3.   int w;
  4.   list *next;
  5. };
  6.  
  7. struct comp{
  8. int parent;
  9. };
  10.  
  11. void make_set(comp set, int v){
  12. set[v].parent=v;
  13. }
  14.  
  15. int find(comp set, int v){
  16. if(set[v].parent==v) return v;
  17. else return find(set, set[v].parent);
  18. }
  19.  
  20. void union(comp set, int u, int v){
  21. int a=find(set, u);
  22. int b=find(set, v);
  23. if(a!=b){
  24.  set[a].parent=b;
  25. }
  26. }
  27.  
  28. list *pop(list *L){
  29. list *tmp=L;
  30. L=L->next;
  31. return tmp;
  32. }
  33.  
  34. List *sort{List *L;}
  35.  
  36. int MST(Graph **G, int n){
  37.     list *Edges=new list;
  38.     Edges=NULL;
  39.     list *G=new list;
  40.     G->next=Edges;
  41.     for(int i=0;i<n;i++){
  42.         for(int j=0;j<n;j++){
  43.             if(G[j][i]!=-1?){
  44.                 list *nowy=new list;
  45.                 nowy->u=j;
  46.                 nowy->v=i;
  47.                 nowy->w=G[j][i];
  48.                 if(Edges==NULL){
  49.                 nowy=Edges;
  50.                 Edges->next=NULL;}
  51.                 else{
  52.                     Edges->next=nowy;
  53.                     Edges=Edges->next;
  54.                     nowy->next=NULL;
  55.                 }
  56.         }
  57.         }
  58.     }
  59.     Edges=G->next;
  60.    List *complete=List *sort(Edges);
  61.    comp set[n];
  62.    int counter=0;
  63.    int total_weight=0;
  64.    while(counter!=n){
  65.    list *act=pop(complete);
  66.    if(find(set, act->u)!=find(set, act->v)){
  67.     counter++;
  68.     total_weight+=act->w;
  69.     union(set, act->u, act->v);
  70.    }
  71.    }
  72.    return total_weight;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement