Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #define NUM 100
- using namespace std;
- int a[NUM][NUM]; //Ma trận trọng số
- int batdau[NUM]; //Đỉnh đầu
- int ketthuc[NUM]; //Đỉnh cuối
- int w[NUM];// Lưu trọng số từng cạnh
- int T[NUM]; // Lưu cây khung
- bool check[NUM];// Đánh dấu
- int length; //Độ dài
- int n; //Số đỉnh
- int socanh; //Số cạnh
- int idx;
- void Kruskal(){
- cin >> n;
- idx = 0;
- length = 0;
- for(int i = 1; i<=n; i++){
- check[i] = false;
- T[i] = 0;
- }
- socanh = 0;
- for(int i = 1; i<=n; i++){
- for(int j = 1; j <=n; j++){
- cin >> a[i][j];
- if(a[i][j]!=0&&a[i][j]!=9999){
- socanh++;
- batdau[socanh] = i;
- ketthuc[socanh] = j;
- w[socanh] = a[i][j];
- }
- }
- }
- for(int i = 1; i<= socanh-1; i++){
- for(int j = i+1; j<=socanh; j++){
- if(w[i] > w[j]){
- int temp = w[i]; w[i] = w[j]; w[j] = temp;
- int temp2 = batdau[i]; batdau[i] = batdau[j]; ketthuc[j] = temp2;
- int temp3 = ketthuc[i]; ketthuc[i] = ketthuc[j]; ketthuc[j] = temp3;
- }
- }
- }
- for(int i = 1; i<=socanh; i++){
- cout << "(" << batdau[i] << "," << ketthuc[i] << ")" << "weight = " << w[i]<<endl;
- }
- for(int i = 1; i<=socanh; i++){
- if(check[batdau[w[i]]]&&check[ketthuc[w[i]]]){
- continue;
- }else{
- idx++;
- T[idx] = i;
- length+=w[i];
- }
- }
- cout << "The Minimum length of spanning tree is " << length << endl;
- cout << "Tree included these edges" << endl;
- for(int i = 1; i<=idx; i++){
- cout << "(" << batdau[T[i]] << "," << ketthuc[T[i]] << ")" << endl;
- }
- }
- int main(){
- Kruskal();
- cout<<"Lost Tech" << endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment