USACO2005 Mar. 干草危机

USACO2005 Mar. Out of Hay
2017年7月15日
Kruskal算法记录最长边


#include
#include
#include
#include
#include
using namespace std;

int N, M;
struct Edges{
    int x, y, Length;
}E[11000];
int ans = 0;
int maxLength;
int FatherVertex[2100];

bool cmp(Edges a, Edges b){return a.Length < b.Length;}

inline void UnionVertex(int a, int b){FatherVertex[FatherVertex[a]] = FatherVertex[b];}

inline int GetFatherVertex(int a){
    if(FatherVertex[a] != a)    FatherVertex[a] = GetFatherVertex(FatherVertex[a]);
    return FatherVertex[a];
}

int main()
{
    cin >> N >> M;
    int a, b, c;
    for(int i = 1; i <= M; i++){
        cin >> a >> b >> c;
        E[++ans].Length = c;
        E[ans].x = a;   E[ans].y = b;
    }
    sort(E + 1, E + 1 + M, cmp);
    for(int i = 1; i <= N; i++)     FatherVertex[i] = i;
    for(int i = 1; i <= M; i++)
        if(GetFatherVertex(E[i].x) != GetFatherVertex(E[i].y))
        {
            UnionVertex(E[i].x, E[i].y);
            maxLength = E[i].Length;
        }
    cout << maxLength << endl;
    return 0;
}

你可能感兴趣的:(USACO2005 Mar. 干草危机)