Description:
Your task is to design the network for the area, so that there is a connection (direct or indirect) between every two points (i.e., all the points are interconnected, but not necessarily by a direct cable), and that the total length of the used cable is minimal.
The maximal number of points is 50. The maximal length of a given route is 100. The number of possible routes is unlimited. The nodes are identified with integers between 1 and P (inclusive). The routes between two points i and j may be given as i j or as j i.
1 0 2 3 1 2 37 2 1 17 1 2 68 3 7 1 2 19 2 3 11 3 1 7 1 3 5 2 3 89 3 1 91 1 2 32 5 7 1 2 5 2 3 7 2 4 8 4 5 11 3 5 10 1 5 6 4 2 12 0
0 17 16 26
题目大意:
给定某两点的无项边权关系, 求由这些点构成的最小生成树的权值是多少。
解题思路:
裸最小生成树模板, 这里用并查集实现最小生成树比较容易,没有太大的坑点。
代码:
#include <iostream>
#include <sstream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iomanip>
#include <utility>
#include <string>
#include <cmath>
#include <vector>
#include <bitset>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
using namespace std;
/*tools:
*ios::sync_with_stdio(false);
*freopen("input.txt", "r", stdin);
*/
typedef long long ll;
typedef unsigned long long ull;
const int dir[5][2] = {0, 1, 0, -1, 1, 0, -1, 0, 0, 0};
const ll ll_inf = 0x7fffffff;
const int inf = 0x3f3f3f;
const int mod = 1000000;
const int Max = (int) 1e6;
struct node {
int l, r;
int w;
}arr[Max];
int Fa[Max], n, m;
void Init() {
for (int i = 1; i <= n; ++i) {
Fa[i] = i;
arr[i].w = inf;
}
}
bool cmp(node a, node b) {
return a.w < b.w;
}
int Pa(int x) {
return (x == Fa[x]) ? x : Pa(Fa[x]);
}
void Merge(int x, int y) {
int fx = Pa(x);
int fy = Pa(y);
Fa[fx] = fy;
}
int main() {
//freopen("input.txt", "r", stdin);
while (scanf("%d", &n) && n) {
Init();
scanf("%d", &m);
for (int i = 0; i < m; ++i) {
int l, r, w;
scanf("%d %d %d", &l, &r, &w);
arr[i].l = l;
arr[i].r = r;
arr[i].w = w;
}
sort(arr, arr + m, cmp);
int rst = n, ans = 0;
for (int i = 0; i < m && rst > 1; ++i) {
if (Pa(arr[i].l) != Pa(arr[i].r)) {
Merge(arr[i].l, arr[i].r);
ans += arr[i].w;
rst--;
}
}
printf("%d\n", ans);
}
return 0;
}