Nyoj 434&&Hud 1301 Jungle Roads[最小生成树Kruscal]

题目链接:气点

/*
  Nyoj 434 Jungle Rode
  Kruscal 写的.算是裸的最下生成树吧!
  输入上有点坑,cin过的。
*/
#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
const int N=30;
const int MAX=250;
struct Island
{
    int x,y;
    int len;
}island[MAX];
bool cmp(Island a,Island b)
{
    if(a.len<b.len) return true;
    return false;
}
int n,top,father[N];
void intput()
{
    char c;
    int LNum;
    top=0;
    for(int i=1;i<n;i++)
    {
        cin>>c>>LNum;
        int temp;
        char ctemp;
        for(int j=1;j<=LNum;j++)
        {
            cin>>ctemp>>temp;
            island[top].x=c-'A'+1;
            island[top].y=ctemp-'A'+1;
            island[top].len=temp;
            top++;
        }
        getchar();
    }
}
int Find_Father(int x)
{
    if(x!=father[x])
    father[x]=Find_Father(father[x]);
    return father[x];
}
void kruscal()
{
    int min=0;
    for(int i=0;i<=N;i++)
    father[i]=i;
    sort(island,island+top,cmp);
    for(int i=0;i<top;i++)
    {
        int a=Find_Father(island[i].x);
        int b=Find_Father(island[i].y);
        if(a!=b)
        {
            father[a]=b;
            min+=island[i].len;
        }
    }
    printf("%d\n",min);
}
int main()
{
    while(scanf("%d",&n)&&n)
    {
        getchar();
        intput();
        kruscal();
    }
}
/*
  kruscal小小的模板
*/
const int N=?
const int MAX=?
struct Rode
{
    int xpoint,ypoint;
    int lenth;
}rode[MAX];
void Init()
{
    for(int i=0;i<N;i++)
    father[i]=i;
}
int Find_Father(int x)
{
    if(x!=father[x])
    father[x]=Find_Father(father[x]);
    return father[x];
}
int Kruscal()
{
    int min=0;
    Init();
    for(int i=0;i<=MAX;i++)
    {
        int a=Find_Father(rode[i].xpoint);
        int b=Find_Father(rode[i].ypoint);
        if(a!=b)
        {
            father[a]=b;
            min+=rode[i].lenth;
        }
    }
    return min;
}

还需要用量变到质变,多做题。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值