kruskal_poj 2485 Highways

此題關鍵要理解輸出的定義

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];
}
void LINK(int x, int y){
    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){
    LINK(FIND_SET(x), FIND_SET(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;
}


 

發佈了100 篇原創文章 · 獲贊 8 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章