1. 程式人生 > >POJ-1251-Jungle Roads

POJ-1251-Jungle Roads

程序 pat sha ring urn main 因此 pac 方式

鏈接:https://vjudge.net/problem/POJ-1251

題意:

熱帶島嶼Lagrishan的頭長老有問題。幾年前,在村莊之間的額外道路上花了一大筆外援資金。但叢林無情地超越了道路,因此大型公路網絡的維護成本太高。長老理事會必須選擇停止維持一些道路。左上方的地圖顯示了現在使用的所有道路以及維護它們的每月aacms的成本。當然,即使路線不像以前那麽短,也需要在維護道路上的所有村莊之間進行某種方式。首席長老想告訴長老會,他們每月可以花費最少的金額來維持連接所有村莊的道路。在上面的地圖中,村莊標有A到I. 右邊的地圖顯示了最便宜的道路,每月216個aacms。你的任務是編寫一個可以解決這些問題的程序。

思路:

kruskal模板題

代碼:

#include <iostream>
#include <memory.h>
#include <string>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <algorithm>
#include <map>
#include <queue>
#include <math.h>
using namespace std;
typedef long long LL;
const int MAXM = 1000;
const int MAXN = 30;
struct Path
{
    int _l;
    int _r;
    int _value;
    bool operator < (const Path & that)const {
        return this->_value < that._value;
    }
}path[MAXM];

int Father[MAXN];

int Get_F(int x)
{
    return Father[x] = (Father[x] == x) ? x : Get_F(Father[x]);
}

int main()
{
    int t,n,m;
    while (~scanf("%d",&n)&&n)
    {
        for (int i = 1;i<=n;i++)
            Father[i] = i;
        char s[10];
        char node[10];
        int v;
        n--;
        int pos = 0;
        while (n--)
        {
            scanf("%s%d",s,&m);
            while (m--)
            {
                scanf("%s%d",node,&v);
                path[++pos]._l = s[0] - ‘A‘ + 1;
                path[pos]._r = node[0] - ‘A‘ + 1;
                path[pos]._value = v;
            }
        }
        sort(path+1,path+1+pos);
        int sum = 0;
        for (int i = 1;i<=pos;i++)
        {
            int tl = Get_F(path[i]._l);
            int tr = Get_F(path[i]._r);
            if (tl != tr)
            {
                Father[tl] = tr;
                sum += path[i]._value;
            }
        }
        printf("%d\n",sum);
    }

    return 0;
}

  

POJ-1251-Jungle Roads