Answer the question
In order to leave comments, you need to log in
How to optimize the program and code in general?
The program reads data from "1.txt", where the number of columns and rows of the matrix and the matrix itself are stored, then, using the Kruskal algorithm, the program finds the minimum spanning tree and displays its weight
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
ifstream file;
int n = 0;
file.open("1.txt");
file >> n;
vector<vector<int>> matrix(n, vector<int>(n));
vector<int> Q(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
file >> matrix[i][j];
if (matrix[i][j] == 0) {
matrix[i][j] = 999; //infinity
}
}
}
file.close();
int min = 999;
int summ = 0;
int mini, minj = 0;
for (int k = 0; k < n-1; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] <= min && (Q[i] == 0 || Q[j] == 0)) {
min = matrix[i][j];
mini = i; minj = j;
}
else break;
}
}
Q[mini] = Q[minj] = 1;
if(min != 999) summ += min;
cout << "{" << mini +1 << ", " << minj + 1 << "} - " << min << endl;
min = 999;
}
cout << "Weight: " << summ;
return 0;
}
6
0 5 10 14 0 0
5 0 5 6 0 0
10 5 0 7 8 9
14 6 7 0 4 0
0 0 8 4 0 12
0 0 9 0 12 0
Answer the question
In order to leave comments, you need to log in
Your implementation is wrong. Enter test
4
0 1 2 0
1 0 0 2
2 0 0 1
0 2 1 0
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question