POJ 2377 Bad Cowtractors Kruskal算法

#include 
#include 
#include 
using namespace std;
struct Edge
{
    int from, to, cost;
    Edge(int from = 0, int to = 0, int cost = 0) : from(from), to(to), cost(cost) {}
};
vector edges;
int N, M, par[1007], ranks[1007];
bool compareEdge(const Edge &a, const Edge &b)
{
    return a.cost < b.cost;
}
void input()
{
    scanf("%d%d", &N, &M);
    int from, to, cost;
    for (int i = 1; i <= M; i++)
    {
        scanf("%d%d%d", &from, &to, &cost);
        edges.push_back(Edge(from, to, -cost));
        edges.push_back(Edge(to, from, -cost));
    }
}
void init()
{
    for (int i = 0; i <= N; i++)
    {
        par[i] = i;
        ranks[i] = 1;
    }
}
int find(int x)
{
    if (par[x] == x)
    {
        return x;
    }
    else
    {
        return par[x] = find(par[x]);
    }
}
void unite(int x, int y)
{
    x = find(x);
    y = find(y);
    if (x == y)
    {
        return;
    }
    if (ranks[x] < ranks[y])
    {
        par[x] = y;
    }
    else
    {
        par[y] = x;
        if (ranks[x] == ranks[y])
        {
            ranks[x]++;
        }
    }
}
bool same(int x, int y)
{
    return find(x) == find(y);
}
int kruskal(int s)
{
    int ans = 0;
    sort(edges.begin(), edges.end(), compareEdge);
    for (int i = 0; i < edges.size(); i++)
    {
        Edge edge = edges[i];
        if (!same(edge.from, edge.to))
        {
            ans += edge.cost;
            unite(edge.from, edge.to);
        }
    }
    int rootNode = find(1);
    for (int i = 2; i <= N; i++)
    {
        if (rootNode != find(i))
        {
            return -1;
        }
    }
    return ans * (-1);
}
int main()
{
    input();
    init();
    printf("%d\n", kruskal(1));
    return 0;
}

你可能感兴趣的:(图论,算法,数据结构)