标签:++ iostream div false namespace lse space 数据 arch
普普通通的最小生成树,写了一遍prim的,所以用一下克鲁斯卡尔
注意输入数据有多组
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> using namespace std; struct MAP { int x; int y; int cost; }; MAP m[10001]; void quick_sort(int head, int tail) { if (head > tail) { return; } int temp = m[head].cost; int i = head; int j = tail; while (i != j) { while (m[j].cost >= temp && i < j) { j--; } while (m[i].cost <= temp && i < j) { i++; } if (i < j) { MAP t = m[j]; m[j] = m[i]; m[i] = t; } } MAP t = m[head]; m[head] = m[i]; m[i] = t; quick_sort(head, i - 1); quick_sort(i + 1, tail); } int f[101]; void init(int n) { for (int i = 1; i <= n; i++) { f[i] = i; } } int find(int n) { if (n == f[n]) { return n; } int t = find(f[n]); f[n] = t; return t; } void link(int a, int b) { int x = find(a); int y = find(b); if (x != y) { f[x] = f[y]; } } bool search(int a, int b) { int x = find(a); int y = find(b); if (x != y) { return false; } return true; } int main() { int n; while (cin >> n) { int a[101][101] = { 0 }; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cin >> a[i][j]; } } int t = 0; for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { m[t].x = i; m[t].y = j; m[t].cost = a[i][j]; t++; } } quick_sort(0, t - 1); init(n); int sum = 0; for (int i = 0; i < t; i++) { if (search(m[i].x, m[i].y) == false) { sum += m[i].cost; link(m[i].x, m[i].y); } } cout << sum << endl; } return 0; }
标签:++ iostream div false namespace lse space 数据 arch
原文地址:https://www.cnblogs.com/Vetsama/p/12234844.html