N
N
NosferatuZodd2021-09-15 09:25:57
Discrete Math
NosferatuZodd, 2021-09-15 09:25:57

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;
}

Content 1.txt:
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

1 answer(s)
W
Wataru, 2021-09-15
@wataru

Your implementation is wrong. Enter test

4
0 1 2 0
1 0 0 2
2 0 0 1
0 2 1 0

Your program will output only 2 edges, although there should be 3. Because you need to use a system of disjoint sets, and not an array of labels Q.
Then, you can not look for the minimum edge from the remaining ones in the loop, but sort all the edges initially.
Look up pseudocode on wikipedia . Or here is the implementation .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question