# kruskal_poj 2485 Highways

194人阅读 评论(0)

For each test case, you should output a line contains an integer, which is the length of the longest road to be built such that all the villages are connected, and this value is minimum.

Sample Input

1

3
0 990 692
990 0 179
692 179 0

Sample Output

692


#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>

#define MAXEN 280000
#define MAXVN 550

using namespace std;

typedef struct{
int u, v, value;
}Edge;

Edge eg[MAXEN];
int p[MAXVN], rank[MAXVN];
vector<Edge> usedEdge;

void MAKE_SET(int x){
p[x] = x;
rank[x] = 0;
}
int FIND_SET(int x){
if(x != p[x])
p[x] = FIND_SET(p[x]);
return p[x];
}
if(rank[x] > rank[y])  p[y] = x;
else{
p[x] = y;
if(rank[x] == rank[y]) rank[y] += 1;
}
}

void UNION_SET(int x, int y){
}
int cmp(const void *a, const void *b){
return (*(Edge *)a).value - (*(Edge *)b).value;
}

bool cp(Edge a,Edge b){
return a.value < b.value;
}
int kruskal(int en, int vn){
usedEdge.clear();//printf("sfdds");
for(int i = 1; i <= vn; i++) MAKE_SET(i);
qsort(eg,en,sizeof(eg[0]), cmp);
for(int i = 0; i < en; i++){
if(FIND_SET(eg[i].u) != FIND_SET(eg[i].v)){
UNION_SET(eg[i].u,eg[i].v);
usedEdge.push_back(eg[i]);
}
}
int sum = 0;
for(int i = 0; i < usedEdge.size(); i++) sum+=usedEdge[i].value;
sort(usedEdge.begin(), usedEdge.end(), cp);
//printf("\n");
//for(int i = 0; i < usedEdge.size(); i++) printf("%d ", usedEdge[i].value);
return usedEdge[usedEdge.size() - 1].value;
}
int main(){
int t, vn;
while(scanf("%d", &t) != EOF){
//getchar();
while(t--){
//getchar();
scanf("%d", &vn);
int a;
int count = 0;
for(int i = 1; i <= vn; i++){
for(int j = 1; j <= vn; j++){
scanf("%d",&a);
if(i != j){
eg[count].u = i;
eg[count].v = j;
eg[count++].value = a;
}
}
}

int len = vn?kruskal(count, vn):0;
printf("%d\n", len);
}
}
return 0;
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：102823次
• 积分：1837
• 等级：
• 排名：千里之外
• 原创：99篇
• 转载：12篇
• 译文：0篇
• 评论：6条
评论排行
最新评论