poj 1251 Jungle Roads(最小生成树)

简单的最小生成树,初学者可以拿来练练手

#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<cmath>
using namespace std;
const int N = 30;

int root[N];

struct Edge
{
    int from,to,cost;
    Edge()
    {

    }
    Edge(const int& from , const int& to,const int& cost):from(from),to(to),cost(cost) {};
    Edge(const Edge& res)
    {
        (*this).from = res.from;
        (*this).to= res.to;
        (*this).cost = res.cost;
    }
    bool operator < ( const Edge& res) const
    {
        return (*this).cost < res.cost;
    }
};

void InitSet(int n)
{
    for(int i = 1 ; i <= n ; i++)
    {
        root[i] = i;
    }
}

int FindSet(int x)
{
    if(x != root[x])
    {
        root[x] = FindSet(root[x]);
    }
    return root[x];
}

void UnionSet(int a,int b)
{
    int x = FindSet(a);
    int y = FindSet(b);
    if(x != y)
    {
        root[x] = y;
    }
}

vector<Edge>v;

void InitGraph(int n)
{
    v.clear();
    string from,to;
    int num,cost;
    for(int i = 0 ; i < n ; i++)
    {
        cin>>from>>num;
        for(int j = 0 ; j < num ; j++)
        {
            cin>>to>>cost;
            v.push_back(Edge(from[0] - 'A' + 1,to[0] - 'A' + 1,cost));
        }
    }

}

int MST(int n)
{
    int ans = 0;
    InitSet(n);
    sort(v.begin(),v.end());
    for(vector<Edge>::iterator it = v.begin() ; it != v.end() ; it++)
    {
        int a = (*it).from;
        int b = (*it).to;
        int cost = (*it).cost;
        if( FindSet(a) != FindSet(b) )
        {
            UnionSet(a,b);
            ans += cost;
        }
    }
    return ans;
}


int main()
{
#ifdef LOCAL
    freopen("in.txt","r",stdin);
#endif // LOCAL
    int n;
    while(scanf("%d",&n) && n)
    {
        InitGraph(n-1);
        int ans = MST(n);
        cout<<ans<<endl;
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值