思路:
將所有的邊按照降序排列,從大到小逐一挑選邊,當已經挑選的邊組成的連通分支中,最大的一個連通分支含有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;
}