題目:求最大生成樹的最小邊。
分析:圖論,最小生成樹,并查集。利用kruskal算法求解即可。
說明:╮(╯▽╰)╭。
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
typedef struct _enode
{
int point1;
int point2;
int weight;
}enode;
enode edge[10001];
//union_set
int sets[101];
int rank[101];
void set_inital(int a, int b)
{
for ( int i = a; i <= b; ++ i) {
rank[i] = 0;
sets[i] = i;
}
}
int set_find(int a)
{
if (a != sets[a])
sets[a] = set_find(sets[a]);
return sets[a];
}
void set_union(int a, int b)
{
if (rank[a] < rank[b])
sets[a] = b;
else {
if (rank[a] == rank[b])
rank[a] ++;
sets[b] = a;
}
}
//end_union_set
int cmp_e(enode a, enode b)
{
return a.weight > b.weight;
}
int kruskal(int n, int m)
{
sort(edge, edge+m, cmp_e);
set_inital(0, n);
int ans = 0;
for (int i = 0; i < m; ++ i) {
int A = set_find(edge[i].point1);
int B = set_find(edge[i].point2);
if (A != B) {
set_union(A, B);
ans = edge[i].weight+0LL;
}
}
return ans;
}
int main()
{
int t, n, m;
while (~scanf("%d",&t))
for (int k = 1; k <= t; ++ k) {
scanf("%d%d",&n,&m);
for (int i = 0; i < m; ++ i)
scanf("%d%d%d",&edge[i].point1,&edge[i].point2,&edge[i].weight);
printf("Case #%d: %d\n",k,kruskal(n, m));
}
return 0;
}