POJ 2485 Highways

题意:给一个完全图,问最小生成树的最大边多大。

解法:Kruskal。

代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<math.h>
#include<limits.h>
#include<time.h>
#include<stdlib.h>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#define LL long long
using namespace std;
int table[505][505];
struct node
{
    int u, v, val;
    node(int u, int v, int val) : u(u), v(v), val(val) {}
    node() {}
    bool operator < (const node &tmp) const
    {
        return val < tmp.val;
    }
};
int father[505];
int Find(int a)
{
    if(father[a] != a)
        father[a] = Find(father[a]);
    return father[a];
}
bool Union(int a, int b)
{
    int c = Find(a), d = Find(b);
    if(c != d)
    {
        father[c] = d;
        return true;
    }
    return false;
}
vector <node> edge;
int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        int n;
        for(int i = 0; i < 500; i++)
            father[i] = i;
        edge.clear();
        scanf("%d", &n);
        for(int i = 0; i < n; i++)
            for(int j = 0; j < n; j++)
            {
                scanf("%d", &table[i][j]);
                if(j > i) edge.push_back(node(i, j, table[i][j]));
            }
        sort(edge.begin(), edge.end());
        int cnt = 0;
        int len = edge.size();
        for(int i = 0; i < len; i++)
        {
            if(Union(edge[i].u, edge[i].v))
                cnt++;
            if(cnt == n - 1)
            {
                printf("%d
", edge[i].val);
                break;
            }
        }
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/Apro/p/4778214.html