hdu6958:KD-Graph

题目链接

题意:给你一张 n n n个点, m m m条边的图,边权为 w w wi,当 w ( u , v ) < = D w(u,v)<=D w(u,v)<=D,就认为他们是在同一组的点,先要你求一个最小的 D D D,是所有点恰好被分为 k k k

解法:并查集维护在同一组内的点,并用一个 c n t cnt cnt记录并查集中 p r e [ i ] = = i pre[i]==i pre[i]==i的个数, c n t cnt cnt即为当前点的组数,按边权把边的信息从大到小排列,然后遍历边,当当前访问的边和上一次访问的边权值不同时,更新答案 a n s ans ans为当一次询问的边的权值(上一次询问已处理,这次询问还没处理),并且判断 c n t cnt cnt k k k的大小关系,如果 k = = c n t k==cnt k==cnt,那 a n s ans ans即为最小答案,如果 c n t < k cnt<k cnt<k,那么不存在,因为 c n t cnt cnt只会越来越小,否则继续遍历

AcCode

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<map>
#include<thread>
#include<set>

//#define int long long
#define inf 0x3f3f3f3f

using namespace std;

inline int max(int a, int b) { return (a > b) ? a : b; }
inline int min(int a, int b) { return (a < b) ? a : b; }
inline int number(char c) { return c - '0'; }

const int N = 1e6 + 100;

struct node {
    int u, v, w;
}edge[N];

int pre[N];
int cnt;

bool cmp(node a, node b) { return a.w < b.w; }
inline int find(int x) { return (x == pre[x]) ? x : pre[x] = find(pre[x]); }
inline void solve(int x, int y) {
    int fx = find(x);
    int fy = find(y);
    if (fx != fy) {
        cnt--;
        pre[fx] = fy;
    }
}

signed main() {
    //std::ios::sync_with_stdio(false);
    //std::cin.tie(0);
    //std::cout.tie(0);
    int t; scanf("%d", &t);
    while (t--) {
        int n, m, k, ans = 0;
        scanf("%d %d %d", &n, &m, &k);
        for (int i = 1; i <= m; i++) scanf("%d %d %d", &edge[i].u, &edge[i].v, &edge[i].w);
        if (n == k) {
            printf("0\n");
            continue;
        }
        for (int i = 1; i <= n; i++) pre[i] = i;
        cnt = n;
        sort(edge + 1, edge + m + 1, cmp);
        for (int i = 1; i <= m; i++) {
            if (edge[i].w != edge[i - 1].w && cnt <= k) { ans = edge[i - 1].w; break; }
            solve(edge[i].u, edge[i].v);

        }
        if (cnt == k)  printf("%d\n", ans);
        else  printf("-1\n");
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值