Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- const int INF = 1000000;
- class Graph
- {
- private:
- bool orient;
- int n, **arr, shet_reber, **min_ost;
- public:
- Graph (int **matrix, int x, int shet)
- {
- n = x;
- arr = matrix;
- shet_reber = shet;
- }
- void get_span_tree();
- void add_edge(int a, int b);
- void init_min_ost();
- void get_min_ost();
- };
- void Graph::get_min_ost()
- {
- int path_length = 0;
- for (int i =0; i < n; i++)
- for (int j = i; j < n; j++)
- path_length += min_ost[i][j];
- cout << path_length << endl;
- for (int i = 0; i < n; i++)
- {
- for (int j = 0; j < n; j++)
- {
- cout.width(3);
- cout << min_ost[i][j] << " ";
- }
- cout << endl;
- }
- }
- void Graph::init_min_ost()
- {
- min_ost = new int*[n];
- for (int i =0; i < n; i++)
- min_ost[i] = new int[n];
- for (int i = 0; i < n; i++)
- for (int j = 0; j < n; j++)
- min_ost[i][j] = 0;
- }
- void Graph::add_edge(int a, int b)
- {
- min_ost[a][b] = arr[a][b];
- min_ost[b][a] = min_ost[a][b];
- }
- void Graph::get_span_tree()
- {
- init_min_ost();
- int wmin;
- int i, j, znach, *B = new int[n];
- B[0] = -1;
- for (i = 1; i < n; i++)
- B[i] = 0;
- for (i = 1; i < n; i++)
- {
- wmin = INF;
- znach = 0;
- for (j = 1; j < n; j++)
- if (B[j] != -1 && wmin > arr[j][B[j]])
- {
- znach = j;
- wmin = arr[j][B[j]];
- }
- if (!znach)
- return;
- add_edge(znach, B[znach]);
- B[znach] = -1;
- for (j = 1; j < n; j++)
- if (B[j] != -1 && arr[j][B[j]] > arr[j][znach])
- B[j] = znach;
- }
- get_min_ost();
- }
- int main()
- {
- int n, shet_reber = 0;
- cin >> n;
- int **arr = new int*[n];
- for ( int i = 0; i < n; i++)
- arr[i] = new int[n];
- for (int i =0; i < n; i++)
- for (int j =0; j < n; j++)
- {
- cin >> arr[i][j];
- if (arr[i][j] == 0)
- arr[i][j] = INF;
- else shet_reber++;
- }
- shet_reber /= 2;
- Graph object(arr, n, shet_reber);
- object.get_span_tree();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement