好长时间没碰电脑了,决定把简单的东西再过一遍,同时加深理解,提高认知,对其有更深的认识。
比较常用的应该改是kruscal了。
kruscal是用边做的,把边排序,然后按顺序加边,直到形成一棵树。
今天的例题是个简单题。
poj2485
就不翻译了,应该可以看懂。
显然是直接用最小生成树,然后再找边的时候,保存最后一次加的边的长度,即为最终答案。
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct edge{
int u,v,w;
};
int readInt(){
int a=0;
char c=getchar();
for(;c<'0'||c>'9';c=getchar()){}
for(;c>='0'&&c<='9';c=getchar()){
a=a*10+c-'0';
}
return a;
}
int T;
int n;
edge e[250005];
int p[505];
int cnt;
int ans;
int cmp(edge a,edge b){
return a.w<=b.w;
}
int find(int cur){
return cur==p[cur]?p[cur]:find(p[cur]);
}
void work(){
ans=0;
for(int i=1;i<=n;i++){
p[i]=i;
}
sort(e,e+cnt,cmp);
for(int i=0;i<cnt;i++){
int x=find(e[i].u),y=find(e[i].v);
if(x!=y){
ans=max(ans,e[i].w);
p[x]=y;
}
}
}
int main(){
T=readInt();
while(T--){
n=readInt();
cnt=0;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
int w;
w=readInt();
if(j>i){
e[cnt].w=w;
e[cnt].u=i;
e[cnt].v=j;
cnt++;
}
}
}
work();
printf("%d\n",ans);
}
return 0;
}