anhkiet2507

Kờ rút can

Jun 11th, 2022 (edited)
802
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1. #include<iostream>
  2. #define NUM 100
  3. using namespace std;
  4. int a[NUM][NUM]; //Ma trận trọng số
  5. int batdau[NUM]; //Đỉnh đầu
  6. int ketthuc[NUM]; //Đỉnh cuối
  7. int w[NUM];// Lưu trọng số từng cạnh
  8. int T[NUM]; // Lưu cây khung
  9. bool check[NUM];// Đánh dấu
  10. int length; //Độ dài
  11. int n; //Số đỉnh
  12. int socanh; //Số cạnh
  13. int idx;
  14. void Kruskal(){
  15.     cin >> n;
  16.     idx = 0;
  17.     length = 0;
  18.     for(int i = 1; i<=n; i++){
  19.         check[i] = false;
  20.         T[i] = 0;
  21.     }
  22.     socanh = 0;
  23.     for(int i = 1; i<=n; i++){
  24.         for(int j = 1; j <=n; j++){
  25.             cin >> a[i][j];
  26.             if(a[i][j]!=0&&a[i][j]!=9999){
  27.                 socanh++;
  28.                 batdau[socanh] = i;
  29.                 ketthuc[socanh] = j;
  30.                 w[socanh] = a[i][j];
  31.             }
  32.         }
  33.     }
  34.     for(int i = 1; i<= socanh-1; i++){
  35.         for(int j = i+1; j<=socanh; j++){
  36.             if(w[i] > w[j]){
  37.                 int temp = w[i]; w[i] = w[j]; w[j] = temp;
  38.                 int temp2 = batdau[i]; batdau[i] = batdau[j]; ketthuc[j] = temp2;
  39.                 int temp3 = ketthuc[i]; ketthuc[i] = ketthuc[j]; ketthuc[j] = temp3;
  40.             }
  41.         }
  42.     }
  43.     for(int i = 1; i<=socanh; i++){
  44.         cout << "(" << batdau[i] << "," << ketthuc[i] << ")" << "weight = " << w[i]<<endl;
  45.     }
  46.     for(int i = 1; i<=socanh; i++){
  47.         if(check[batdau[w[i]]]&&check[ketthuc[w[i]]]){
  48.             continue;
  49.         }else{
  50.             idx++;
  51.             T[idx] = i;
  52.             length+=w[i];
  53.         }
  54.     }
  55.     cout << "The Minimum length of spanning tree is " << length << endl;
  56.     cout << "Tree included these edges" << endl;
  57.     for(int i = 1; i<=idx; i++){
  58.         cout << "(" << batdau[T[i]] << "," << ketthuc[T[i]] << ")" << endl;
  59.     }
  60. }
  61.  
  62. int main(){
  63.     Kruskal();
  64.     cout<<"Lost Tech" << endl;
  65.     return 0;
  66. }
  67.  
Add Comment
Please, Sign In to add comment