POJ-2485 Highways---最小生成树中最大边

时间:2022-12-10 16:41:13

题目链接:

https://vjudge.net/problem/POJ-2485

题目大意:

求最小生成树中的最大边

思路:

是稠密图,用prim更好,但是规模不大,kruskal也可以过

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<sstream>
using namespace std;
typedef long long ll;
const int maxn = 3e5 + ;
const int INF = << ;
int dir[][] = {,,,,-,,,-};
int T, n, m, x;
struct edge
{
int u, v, w;
bool operator <(const edge& a)const
{
return w < a.w;
}
};
edge a[maxn];
int par[], high[];
//初始化n个元素
void init(int n)
{
for(int i = ; i < n; i++)
{
par[i] = i;
high[i] = ;
}
}
//查询树的根
int Find(int x)
{
return par[x] == x ? x : par[x] = Find(par[x]);//路径压缩
}
void unite(int x, int y)
{
x = Find(x);
y = Find(y);
if(x == y)return;
if(high[x] < high[y])par[x] = y;//y的高度高,将x的父节点设置成y
else
{
par[y] = x;
if(high[x] == high[y])high[x]++;
}
}
bool same(int x, int y)
{
return Find(x) == Find(y);
}
void kruskal(int n, int m)//点数n,边数m
{
int ans = ;//mst权值
int num= ;//已经选择的边的边数
sort(a, a + m);//边进行排序
init(n);//初始化并查集
for(int i = ; i < m; i++)
{
int u = a[i].u;
int v = a[i].v;
if(Find(u - ) != Find(v - ))//图最开始的下标是1,并查集是0
{
//printf("%d %d %d\n", u, v, a[i].w);
//sum_mst += a[i].w;
ans = max(ans, a[i].w);
num++;
unite(u - , v - );
}
if(num >= n - )break;
}
//printf("weight of mst is %d\n", sum_mst);
printf("%d\n", ans);
}
int main()
{
cin >> T;
while(T--)
{
scanf("%d", &n);
int x;
int tot = ;
for(int i = ; i <= n; i++)
{
for(int j = ; j <= n; j++)
{
scanf("%d", &x);
if(i == j)continue;
a[tot].u = i;
a[tot].v = j;
a[tot++].w = x;
}
}
kruskal(n, tot);
}
return ;
}