题目链接:https://vjudge.net/problem/CodeForces-893C
题目大意:
有n个人,其中有m对朋友,现在你有一个秘密你想告诉所有人,第i个人愿意出价a[i]买你的秘密,获得秘密的人会免费告诉它的所有朋友(他朋友的朋友也会免费知道),现在他们想出最少的价钱买秘密,那么你最少能得到多少钱?
#include <stdio.h> #include <math.h> #include <stdlib.h> #define min(a,b) (a>b?b:a) int pre[100005]; int find(int x) { int r = x; while (pre[r] != r) r = pre[r]; int i = x; int j; while (pre[i] != r) { j = pre[i]; pre[i] = r; i = j; } return r; } void join(int a, int b) { int f1=find(a); //超时的错误就出现在这,我写成pre[a]了 int f2=find(b); if (f1 != f2) { pre[f2] = f1; } } int main() { int n, m, i, j,a,b; long long g[100005],sum; while (scanf("%d%d", &n, &m) != EOF) { for (i = 1; i <=n; i++) { scanf("%lld", &g[i]); } for (i = 1; i <= n; i++) { pre[i] = i; } for (i = 0; i < m; i++) { scanf("%d%d", &a, &b); join(a, b); } for (i = 1; i <= n; i++) { g[find(i)] = min(g[i], g[find(i)]); } sum = 0; for (i = 1; i <= n; i++) { if (pre[i] == i)sum += g[i]; } printf("%lld\n", sum); } return 0; }
2018-04-02