题意:给出一个树形图和边权值,边权值是容量,问把某个点作为首都,向其他n-1个点运输货物,货物容量不超过路径上的边权值;问可以输出的最大货物是多少?
思路:这个题目一开始只想到了使用并查集来做,但是具体使值最大的方法却没有想到,后来问了别人才想明白这个地方,把所有城市之间的道路按权值从大到小排序,然后我们可以保证当前所选择的这一条道路的权值与已经建立的图里面路相比较是最短的,我们将要加入这一条边的集合与要加入的集合进行比较,比较当前这一条边加入哪一个集合会使值更大,然后最后所得到就是最大值。
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#define MAXN 200010
#define INF 10000000
#define MOD 1000000007
#define LL long long
using namespace std;
LL n;
LL par[MAXN];
LL rank1[MAXN];
LL sum[MAXN];
void init() {
for (LL i = 0; i <= n; ++i) {
par[i] = i;
rank1[i] = 1;
}
memset(sum, 0, sizeof(sum));
}
LL find(LL x) {
if (x == par[x])
return x;
return par[x] = find(par[x]);
}
void unite(LL x, LL y, LL z) {
x = find(x);
y = find(y);
if (sum[x] + rank1[y] * z > sum[y] + rank1[x] * z) {
sum[x] = sum[x] + rank1[y] * z;
par[y] = x;
rank1[x] += rank1[y];
} else {
sum[y] = sum[y] + rank1[x] * z;
par[x] = y;
rank1[y] += rank1[x];
}
}
struct Node {
LL from;
LL to;
LL cost;
};
Node edge[MAXN];
bool cmp(const Node &x1, const Node &x2) { return x1.cost > x2.cost; }
int main() {
//std::ios::sync_with_stdio(false);
while (~scanf("%lld", &n)) {
memset(edge, 0, sizeof(edge));
init();
for (LL i = 0; i < n - 1; ++i) {
scanf("%lld%lld%lld", &edge[i].from, &edge[i].to, &edge[i].cost);
}
sort(edge, edge + n - 1, cmp);
for (LL i = 0; i < n - 1; ++i) {
unite(edge[i].from, edge[i].to, edge[i].cost);
}
printf("%lld\n", sum[find(1)]);
}
return 0;
}