我是靠谱客的博主 健忘流沙,最近开发中收集的这篇文章主要介绍HDU 6958 KD-Graph(带权并查集),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

题目链接:KD-Graph

Problem Description

Let’s call a weighted connected undirected graph of n vertices and m edges KD-Graph, if the
following conditions fulfill:

  • n vertices are strictly divided into K groups, each group contains at least one vertice

  • if vertices p and q ( p ≠ q ) are in the same group, there must be at least one path between p and q meet the max value in this path is less than or equal to D.

  • if vertices p and q ( p ≠ q ) are in different groups, there can’t be any path between p and q meet the max value in this path is less than or equal to D.

You are given a weighted connected undirected graph G of n vertices and m edges and an integer K.

Your task is find the minimum non-negative D which can make there is a way to divide the n vertices into K groups makes G satisfy the definition of KD-Graph.Or −1 if there is no such D exist.

Input

The first line contains an integer T (1≤ T ≤5) representing the number of test cases.
For each test case , there are three integers n,m,k(2≤n≤100000,1≤m≤500000,1≤k≤n) in the first line.
Each of the next m lines contains three integers u,v and c (1≤v,u≤n,v≠u,1≤c≤109) meaning that there is an edge between vertices u and v with weight c.

Output

For each test case print a single integer in a new line.

Sample Input

2
3 2 2
1 2 3
2 3 5
3 2 2
1 2 3
2 3 3

Sample Output

3
-1

题目大意:

给我们一个n个顶点,m条边构成的加权连通无向图, 将n个顶点严格划分成k组,要求满足两个条件

  1. 如果两个顶点在同一组,这两点之间必须至少有一条路径满足这条路径中的最大值小于等于D
  2. 如果两个顶点不在同一组,这两点之间不存在满足该路径中最大值小于等于D的路径。

输出能严格划分为K组的D的最小值,否则输出-1

思路:

我们假设已知D的最小值,根据题目条件我们可以得出,同一个集合内所有边权小于等于D的点必须同属一组,否则就不满足条件

我们可以对边权进行升序排序,开始将n个点分为n组,按边权从小到大依次进行并查集的操作,每两个点合并就让n – ,如果当前边与上一条边权不相同,且恰好n==k,那么就满足条件输出答案,否则n<k就输出-1

代码如下:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <stdio.h>
using namespace std;
typedef long long
ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
const int N = 1e6 + 7, M = 1e6 + 6, mod = 2e5 + 3;
const int inf = 0x3f3f3f3f;
int n, m, k, p[N];
struct edge{
int a, b, w;
}edges[N];
int find(int k)
{
return k == p[k] ? k : p[k] = find(p[k]);
}
bool cmp(edge x, edge y)
{
return x.w < y.w;
}
int main()
{
int t; scanf("%d", &t);
while (t -- )
{
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= n; i ++ ) p[i] = i;
for (int i = 1; i <= m; i ++ )
{
int a, b, c; scanf("%d%d%d", &a, &b, &c);
edges[i] = {a, b, c};
}
sort(edges + 1, edges + m + 1, cmp);
int ans = 0, now = n;
for (int i = 1; i <= m; i ++ )
{
if (edges[i].w != edges[i - 1].w)
{
if (now == k) break;
}
int px = find(edges[i].a), py = find(edges[i].b);
if (px == py) continue;
now -- ;
p[px] = py;
ans = edges[i].w;
}
if (now == k) printf("%dn", ans);
else printf("-1n");
}
return 0;
}

最后

以上就是健忘流沙为你收集整理的HDU 6958 KD-Graph(带权并查集)的全部内容,希望文章能够帮你解决HDU 6958 KD-Graph(带权并查集)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部