思路:
将所有的边按照降序排列,从大到小逐一挑选边,当已经挑选的边组成的连通分支中,最大的一个连通分支含有k个顶点,则算法终止。
代码:
#include<iostream>
#include<algorithm>
using namespace std;
struct Arc
{
int from;
int to;
int weight;
};
bool cmp(const Arc& A, const Arc& B)
{
return A.weight > B.weight;
}
int main()
{
int **G;
int *groupId;
Arc *arc;
int n, m, k;
while(cin >> n >> m >> k)
{
//创建及初始化数组
arc = new Arc[m];
G = new int*[n];
groupId = new int[n];
for(int i = 0; i < n; i++)
{
G[i] = new int[n];
groupId[i] = i;
}
//读取数据
int from, to, weight;
for(int i = 0; i < m; i++)
{
cin >> from >> to >> weight;
G[from - 1][to - 1] = weight;
arc[i].from = from - 1;
arc[i].to = to - 1;
arc[i].weight = weight;
}
//排序
sort(arc, arc + m, cmp);
/*
//debug
for(int i = 0; i < m; i++)
cout << arc[i].from << ' ' << arc[i].to << ' ' << arc[i].weight << endl;
system("pause");
*/
//从大到小逐一挑选边
int maxGroup;
int maxWeight = 0;
for(int i = 0; i < m; i++)
{
maxGroup = 0;
int id = groupId[arc[i].to];
for(int j = 0; j < n; j++)
{
if(groupId[j] == id)
{
groupId[j] = groupId[arc[i].from];
maxGroup++;
}
else if(groupId[j] == groupId[arc[i].from])
maxGroup++;
}
if(maxGroup >= k)
{
maxWeight = arc[i].weight;
break;
}
}
//输出
cout << maxWeight << endl;
//析构数组
for(int i = 0; i < n; i++)
delete[] G[i];
delete[] G;
delete[] arc;
delete[] groupId;
}
//system("pause");
return 0;
}