UVa 1664 (Conquer a New Region) 并查集

本题要求在树形结构的n个城市中找到一个中心城市,使得该中心到所有其他城市的最小通路容量之和最大。通过将边按权值降序排序,采用Kruskal的思路,动态维护每个集合中点的最大容量和数量,不断合并较小集合到较大集合,最终得到的答案即为最大容量。这是一种巧妙的并查集应用策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://cn.vjudge.net/problem/UVA-1664


题意:n个城市形成一棵树,每条边有权值C(i, j)。任意两个点的容量S(i, j)定义为i与j唯一通路容量上的最小值。找一个点(他将成为中心城市),使得它到其他所有点的容量之和最大。


思路:很巧妙地并查集维护问题。首先把所有边按照权值从大到小排序,这样可以确保我们每次选出的边都比已选出的小。接下来按照Kruskal的思路来,假设我们已经维护好了一些集合(点的集合),其中每个集合中某个点到集合中所有点容量和的最大值为sum[i],集合点的数量为cnt[i]。对于下一条被选出的边(u,v,c),设u属于集合X,v属于集合Y,如果我们选择X中的点作为中心城市,则答案为sum[X] + cnt[Y] * c(因为这条边比已经出现的边权值都要小,所以两个集合间必以这条路作为容量),同理,若选Y中点作为中心城市,则答案为sum[Y] + cnt[X] * c,我们取两者中的最大值,将较小值的集合合并到较大值的集合。一步步下去,最终集合的sum值就是答案。


#include<cstdio>
#include<cstring>
#include<string>
#include<cctype>
#include<iostream>
#include<set>
#include<map>
#include<cmath>
#include<sstream>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
#define fin(a) freopen("a.txt","r",stdin)
#define fout(a) freopen("a.txt","w",stdout)
typedef long long LL;
using namespace std;
typedef pair<int, int> P;
const int dx[] = {0, 0, 0, -1, 1};
const int dy[] = {0, -1, 1, 0, 0};
const int INF = 1e8 + 10;
const int maxn = 2e5 + 10;
int fa[maxn];
LL cnt[maxn], sum[maxn];
int n;

int find(int x) {
  return fa[x] == x ? fa[x] : fa[x] = find(fa[x]);
}

struct Edge {
   int from, to, cost;
   Edge(int u, int v, int c) : from(u), to(v), cost(c) {}
   bool operator < (const Edge& rhs) const {
      return cost > rhs.cost;
   }
};

vector<Edge> edges;

int main() {
   int u, v, c;
   while(scanf("%d", &n) == 1) {
      edges.clear();
      for(int i = 1; i <= n; i++) fa[i] = i, cnt[i] = 1, sum[i] = 0;
      for(int i = 1; i < n; i++) {
         scanf("%d%d%d", &u, &v, &c);
         edges.push_back(Edge(u, v, c));
      }
      sort(edges.begin(), edges.end());

      for(int i = 0; i < edges.size(); i++) {
         int u = edges[i].from, v = edges[i].to, c = edges[i].cost;
         int x = find(u), y = find(v);
         if(x != y) {
            if(sum[x] + cnt[y] * (LL)c > sum[y] + cnt[x] * (LL)c) {
               sum[x] += cnt[y] * (LL)c;
               cnt[x] += cnt[y];
               fa[y] = x;
            }
            else {
               sum[y] += cnt[x] * (LL)c;
               cnt[y] += cnt[x];
               fa[x] = y;
            }
         }
      }

      printf("%lld\n", sum[find(1)]);
   }
   return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值