九度1347解題報告

http://ac.jobdu.com/problem.php?pid=1347

孤島連通問題的實質就是求圖的最小生成樹問題,若非連通圖就輸出no。這裏使用的是Kruskal算法,將所有邊排序後,依次判斷是否能讓不連通的兩定點連通,若可以,則併入該邊,把該邊的代價算入總代價。最後輸出從代價,即最小代價,如不連通,則爲no,判斷連通用到了並查集。代碼如下

#include <stdio.h>
#include <algorithm>
using namespace std;

struct road
{
    int a,b,d;
    bool operator < (const road &x) const
    {
        return d<x.d; 
    }
}road[10001];

int root[1001];

int getroot(int x)
{
    if (root[x]==-1) return x;
    else
    {
        int temp=getroot(root[x]);
        root[x]=temp;
        return temp;
    }
}

int main()
{
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout); 
    int n,m;
    while (scanf("%d %d",&n,&m)!=EOF)
    {
        for (int i=0;i<=n;++i) root[i]=-1;
        for (int i=0;i<m;++i)
            scanf("%d %d %d", &road[i].a,&road[i].b,&road[i].d);
        sort(road,road+m);
        int cost=0;
        for (int i=0;i<m;++i)
        {
            int a=getroot(road[i].a);
            int b=getroot(road[i].b);
            if (a!=b)
            {
                root[a]=b;
                cost+=road[i].d;
            }
        }
        int cnt=0;
        for (int i=1;i<=n;++i)
            if (root[i]==-1) ++cnt;
        if (cnt==1) printf("%d\n",cost);
        else printf("no\n");
    }
    return 0;
}


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