Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- const int INF = 10000;
- struct rebro
- {
- int begin, end, ves;
- void new_rebro(int begin, int end, int ves)
- {
- this->begin = begin;
- this->end = end;
- this->ves = ves;
- }
- };
- class Graph
- {
- private:
- int n, shet_reber, dlina = 0;
- int *color, **path;
- rebro *arr;
- public:
- Graph (rebro *matrix, int x, int shet)
- {
- n = x;
- shet_reber = shet;
- arr = matrix;
- color = new int[n];
- for (int i = 0; i < n; i++)
- color[i] = i;
- path = new int*[n];
- for(int i = 0; i < n; i++)
- path[i] = new int[n];
- for(int i = 0; i < n; i++)
- for (int j = 0; j < n; j++)
- path[i][j] = 0;
- }
- void sort_reber(int first, int last);
- void algorithm_kras();
- void get_result_kras();
- };
- void Graph::sort_reber(int first, int last)
- {
- int x, i, j, c = first, d = last;
- while (c < d)
- {
- int m = (c+d)/2;
- if (arr[c].ves > arr[d].ves && arr[c].ves < arr[m].ves)
- x = arr[c].ves;
- else if (arr[d].ves > arr[c].ves && arr[d].ves < arr[m].ves)
- x = arr[d].ves;
- else x = arr[m].ves;
- i = c;
- j = d;
- while (i < j)
- {
- while (arr[i].ves < x)
- i++;
- while (arr[j].ves > x)
- j--;
- if (i <= j)
- {
- swap(arr[i], arr[j]);
- i++;
- j--;
- }
- }
- if (j-c < d-i)
- {
- if (c < j)
- sort_reber(c, j);
- c = i;
- }
- else
- {
- if (i<d)
- sort_reber(i, d);
- d = j;
- }
- }
- }
- void Graph::algorithm_kras()
- {
- for(int i = 0; i < shet_reber; i++)
- {
- if (color[arr[i].begin] != color[arr[i].end])
- {
- path[arr[i].begin][arr[i].end] = arr[i].ves;
- path[arr[i].end][arr[i].begin] = arr[i].ves;
- dlina += arr[i].ves;
- int old_color = color[arr[i].begin], new_color = color[arr[i].end];
- for (int j = 0; j < n; j++)
- if (color[j] == old_color)
- color[j] = new_color;
- }
- }
- }
- void Graph::get_result_kras()
- {
- cout << dlina << endl;
- for (int i = 0; i < n; i++)
- {
- for(int j = 0; j < n; j++)
- {
- cout.width(3);
- cout << path[i][j] << " ";
- }
- cout << endl;
- }
- }
- int main()
- {
- int n, shet_reber, a, b, w;
- cin >> n >> shet_reber;
- rebro *arr = new rebro[shet_reber];
- for (int i = 0; i < shet_reber; i++)
- {
- cin >> a >> b >> w;
- a--;
- b--;
- arr[i].new_rebro(a, b, w);
- }
- Graph object(arr, n, shet_reber);
- object.sort_reber(0, shet_reber-1);
- object.algorithm_kras();
- object.get_result_kras();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement