poj 2377

題意:給你一些邊,把所有點連起來成樹。若能連起來,求出邊最大值的和。若不能輸出-1;

由於給的是邊kruskal比prim要方便。-1WA了好幾發。


#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 20000 + 10;
int pa[1000 + 10];
struct node
{
    int x, y, cost;
    bool operator < (const node &a) const
    {
        return cost > a.cost;
    }
};
node edges[maxn];
int n, m;
int root(int x)
{
    if(pa[x] != x)
        pa[x] = root(pa[x]);
    return pa[x];
}
bool same(int x, int y)
{
    return root(x) == root(y);
}
void unite(int x, int y)
{
    int fx = root(x);
    int fy = root(y);
    pa[fx] = fy;
}
void kruskal()
{
    long long ans = 0;
    for(int i = 0; i < m; i++)
    {
        if(!same(edges[i].x, edges[i].y))
        {
            ans += edges[i].cost;
            unite(edges[i].x, edges[i].y);
        }
    }
    int cnt = 0;
    for(int i = 1; i <= n; i++)
    {
        if(pa[i] == i) cnt++;
    }
    printf("%lld\n", cnt > 1 ? -1 : ans);
}
int main()
{
    while(scanf("%d%d", &n, &m) == 2)
    {
        for(int i = 0; i <= n; i++) pa[i] = i;
        for(int i = 0; i < m; i++)
        {
            scanf("%d%d%d", &edges[i].x, &edges[i].y, &edges[i].cost);
        }
        sort(edges, edges + m);
        kruskal();
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章