Conquer a New Region HDU - 4424

题目传送门

题意:给出一个树形图和边权值,边权值是容量,问把某个点作为首都,向其他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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值