最小生成树(kruskal)
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 505;
int prt[maxn], n;
struct node
{
int u, v, w;
bool operator < (const node &b) const{
return w < b.w;
}
} a[maxn*maxn];
int getpa(int x){return prt[x] == x ? x : prt[x] = getpa(prt[x]);}
int kruskal()
{
int pa1, pa2, cnt = 0, ans = 0;
for(int i = 1; i <= n; i++) prt[i] = i;
for(int i = 1; i <= n*(n-1); i++){
pa1 = getpa(a[i].u);
pa2 = getpa(a[i].v);
if(pa1 != pa2){
prt[pa2] = pa1;
cnt++;
ans = max(ans,a[i].w);
if(cnt == n-1) break;
}
}
return ans;
}
int main()
{
int t; scanf("%d",&t);
int tmp, cnt;
while(t--){
scanf("%d",&n);
cnt = 0;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
scanf("%d",&tmp);
if(i == j) continue;
a[++cnt].u = i;
a[cnt].v = j;
a[cnt].w = tmp;
}
}
sort(a+1,a+cnt+1);
printf("%d\n",kruskal());
}
return 0;
}