KD-Graph
Time Limit: 3000/1500 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2483 Accepted Submission(s): 692
https://acm.hdu.edu.cn/showproblem.php?pid=6958
Problem DescriptionLet’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 −1if there is no such D exist.
InputThe 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.OutputFor each test case print a single integer in a new line.
Sample Input2 3 2 2 1 2 3 2 3 5 3 2 2 1 2 3 2 3 3Sample Output3 -1
算法标签:并查集
题目核心:“找到最小的非负D使有一种方法将n个顶点分成K组使G满足KD-Graph的定义并输出;或者,如果没有这样的D存在”,输出-1。
首先将给定的边集按照权值大小进行排序(因为这样从小到大遍历边集的时候,可以保证在循环体内所有边<=D),初始化并查集,将每个点看作一个连通块,然后遍历边集合,使用并查集查询是否位于同一集合,如果在一个集合就继续(continue),不在同一集合则合并点(此时应该是>k+1),连通块个数-1,并把答案暂定为此时的边的权重,“若某一阶段的全部边合并完,并查集数量为k,则当前阶段合并边的权值就是答案,否则输出-1”(我理解的是直到下一个不同边权即不同组的时候跳出,判断此时组数是否等于k,是则输出ans,否则输出-1)。
#include<iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
using namespace std;
int fa[1000010];
struct m{
int u,v,c;
}edge[1000010];
bool cmp(m s1,m s2)
{
return s1.c<s2.c;
}
int find(int x)
{
if(fa[x]==x) return x;
return fa[x]=find(fa[x]);
}
void join(int x,int y)
{
fa[find(x)]=find(y);
}
int main()
{
int t,n,m,k,now,ans;
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&m,&k);
now=n;
ans=0;
for(int i=1;i<=m;i++)
scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].c);
sort(edge+1,edge+1+m,cmp);
for(int i=1;i<=n;i++) fa[i]=i;//最好从1开始循环?
for(int j=1;j<=m;j++)
{
if(edge[j].c!=edge[j-1].c)
{
if(now==k) break;
}
if(find(edge[j].u)==find(edge[j].v)) continue;
join(edge[j].u,edge[j].v);
now--;
ans=edge[j].c;
}
printf("%d\n",now==k?ans:-1);
}
return 0;
}