我又双叒叕来水博客啦
L i n k Link Link
l u o g u P 2259 luogu\ P2259 luogu P2259
D e s c r i p t i o n Description Description
S a m p l e Sample Sample I n p u t Input Input
5
1 2 3 4 5
4 3 2 1
3 4 5
2 1
5
S a m p l e Sample Sample O u t p u t Output Output
7
H i n t Hint Hint
S o l u t i o n Solution Solution
受
t
j
h
tjh
tjh大佬的推荐,前来做这道题 (水博客)
结果发现这道题和
K
u
g
l
a
r
z
Kuglarz
Kuglarz的代码一毛一样,思路也一样,直接放代码吧
C o d e Code Code
#include<iostream>
#include<cstdio>
#include<algorithm>
#define ll long long
using namespace std;
int n, h, t, x, y, p, f[10001];
ll ans, z;
struct awsl
{
int to, from;
ll val;
}w[10000001];
int find(int x)
{
if (f[x] == x) return x;
return f[x] = find(f[x]);
}
bool cmp(awsl a, awsl b)
{return a.val < b.val;}
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; f[i] = i, ++i)
for (int j = i; j <= n; ++j)
{
scanf("%lld", &z);
w[++t] = (awsl){i - 1, j, z};
w[++t] = (awsl){j, i - 1, z};
}
sort(w + 1, w + t + 1, cmp);
h = 1; p = 1;
while (h <= t && p <= n) {
x = w[h].to, y = w[h].from, z = w[h].val;
if (find(x) != find(y)) {//还不在一个连通块
++p;
ans += z;//累计答案
f[find(x)] = find(y);
}
++h;
}
printf("%lld", ans);
return 0;
}