您的位置:首页 > 产品设计 > UI/UE

poj 2485 highway lightblueme

2013-01-22 17:16 447 查看
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <algorithm>

using namespace std;
#define NUM 505

int father[NUM];
void initroot(){
for(int i=0;i<505;i++)
father[i]=-1;
}
int findroot(int n){
int x=n;
if(father[x]==-1){
return x;
}
x=findroot(father[x]);
return x;
}

struct road{
int from,to;
int cost;
bool operator <(const road& p)const {
return cost<p.cost;
}
};

struct road Roads[NUM*(NUM+1)/2];

int main(){
int T,N;
scanf("%d",&T);
for(int index=0;index<T;index++){
scanf("%d",&N);
int roadi=0;
int temp;
initroot();
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
scanf("%d",&temp);
if(i>j){
Roads[roadi].from=i;
Roads[roadi].to=j;
Roads[roadi].cost=temp;
roadi++;
}
}
}

int edgenum=0;
sort(Roads,Roads+N*(N-1)/2);

int maxl;
for(int k=0;k<N*(N+1)/2;k++){
int from=Roads[k].from;
int to=Roads[k].to;
from=findroot(from);
to=findroot(to);
if(from!=to){//合并
father[from]=to;
edgenum++;
}
if(edgenum==N-1){//当达到N-1条边是算法结束
maxl=Roads[k].cost;
break;
}
}
printf("%d\n",maxl);
}
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: