Advertisement
tungSfer

trr_kruskal

May 19th, 2021
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include <iostream>
  2. #define MAX 100
  3. using namespace std;
  4. struct  edg{ int    d, c, h; };
  5. class dothi{
  6.     int     n, a[MAX][MAX], atree[MAX][MAX];
  7.     public:
  8.     int     ne;
  9.     edg     graph[MAX], tree[MAX];
  10.     bool    chuaxet[MAX];
  11.     void    readdata();
  12.     void    init();
  13.     void    bubblesort();
  14.     void    dfstree(int u);
  15.     void    kruskal();
  16. };
  17. void    dothi::readdata(){
  18.     cin>>n; ne=0;
  19.     for(int i=1; i<=n; i++)
  20.         for(int j=1; j<=n; j++){
  21.             cin>>a[i][j];
  22.             if((a[i][j]!=0)&&(i<j)){
  23.                 ne++;   graph[ne].d=i;  graph[ne].c=j;  graph[ne].h=a[i][j];
  24.             }
  25.         }
  26. }
  27. void    dothi::init(){  for(int i=1; i<=n; i++) chuaxet[i]=true;    }
  28. void    dothi::bubblesort(){
  29.     for(int i=1; i<ne; i++)
  30.         for(int j=ne; j>i; j--)
  31.             if(graph[j].h<graph[j-1].h) swap(graph[j], graph[j-1]);
  32. }
  33. void    dothi::dfstree(int u){
  34.     chuaxet[u]=false;
  35.     for(int i=1; i<=n; i++)
  36.         if((atree[u][i]==1)&&(chuaxet[i]==true)) dfstree(i);
  37. }
  38. void    dothi::kruskal(){
  39.     int dT=0, net=0;
  40.     for(int i=1; i<=n; i++)
  41.         for(int j=1; j<=n; j++) atree[i][j]=0;
  42.     bubblesort();
  43.     for(int i=1; i<=ne; i++){
  44.         init(); dfstree(graph[i].d);
  45.         if(chuaxet[graph[i].c]==true){//bo sung canh i vao cay ko tao nen chu trinh
  46.             int dau=graph[i].d, cuoi=graph[i].c;
  47.             net++;  tree[net].d=dau; tree[net].c=cuoi;
  48.             atree[dau][cuoi]=atree[cuoi][dau]=1;    dT+=graph[i].h;
  49.         }
  50.     }
  51.     cout<<"dH = "<<dT<<endl;
  52.     for(int i=1; i<=net; i++) cout<<tree[i].d<<"   "<<tree[i].c<<endl;
  53. }
  54. int main(){ dothi   g;  g.readdata();   g.kruskal();    }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement