Добавил:
Studfiles2
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:
#include <stdio.h>
#include <algorithm.h>
#include <conio.h>
const int MaxN = 101;
int n, m, s;
struct Tedge { int a, b, c; } R[MaxN * MaxN];
bool U[MaxN * MaxN];
int P[MaxN];
bool operator <(const Tedge& a, const Tedge& b) {
return a.c < b.c;
}
int get(int x)
{
if (P[x] != x) P[x] = get(P[x]);
return P[x];
}
void Join(int x, int y)
{
x = get(x);
y = get(y);
if (x == y) P[x] = y; else P[y] = x;
}
int main()
{
freopen("input.txt", "r", stdin);
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++)
scanf("%d%d%d", &R[i].a, &R[i].b, &R[i].c);
sort(R, R + m);
memset(U, 0, sizeof(U));
s = 0;
for (int i = 1; i <= n; i++) P[i] = i;
for (int i = 1; i <= m; i++)
if (get(R[i].a) != get(R[i].b)) {
Join(R[i].a, R[i].b);
s += R[i].c;
U[i] = true;
}
printf("Ves dereva raven = %d\n", s);
printf("V derevo vhodat rebra:\n");
for (int i = 1; i <= m; i++)
if (U[i]) printf("%d %d\n", R[i].a, R[i].b);
getch();
return 0;
}
Соседние файлы в папке Курсовая работа - Выделение минимального остовного дерева