[kuangbin带你飞]专题六 最小生成树A

166 篇文章 0 订阅
32 篇文章 0 订阅

http://poj.org/problem?id=1251

题意:

题目大意在相通n个岛屿的所有桥都坏了,要重修,重修每一个桥所用的时间不同,求重修使每个岛屿都间接或直接与其他岛屿相同时所用的的最短时间(只有修完一个桥后才可修下一个桥)。
对于数据,数据输入的第一行n代表岛屿的个数,当为0是结束程序,接着n-1行开始时为这岛屿的编号,用大写字母表示,接着是一个整数m,表示与该岛屿连接的字典序大于该岛屿编号的个数,然后该行输入m对数据,每对数据的第一个字母表示与该岛屿连通的岛屿的编号,第二个数字表示要重修两岛屿之间桥所需要的时间,输出数据见样例及原题。

tip:

简言之就是求最小生成树。模板题

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxm = 100;
int n,p,tot ,root[maxm];
char c[2];
struct  node{
    int from,to,w;
    bool operator < (const node &b)const{
        return w < b.w;
    }
}edges[maxm];

void init(){
    tot = 0;
    for(int i = 0; i <= n ; i++)    root[i] = i;
    for(int i = 0 ; i < n-1 ; i++){
        scanf("%s%d",c,&p);
        for(int j = 0 ; j < p ; j++){
            int k;
            scanf("%s%d",c,&k);
           // printf("c = %c,k = %d\n",c[0],k);
            edges[tot].from = i;edges[tot].to = c[0]-'A';edges[tot].w = k;
            tot++;
        }
    }
    sort(edges,edges+tot);
}
int findroot(int x){
    return x==root[x]?x:root[x]=findroot(root[x]);
}
void kru(){
    int ans = 0;
    for(int i = 0 ; i < tot ;i++){
       // printf("       %d\n",edges[i].w);
        int x = findroot(edges[i].to),y = findroot(edges[i].from);
        if(x == y)  continue;
        else{
            ans+=edges[i].w;
            root[x] = root[y];
        }
    }
    printf("%d\n",ans);
}

int main(){
    while(~scanf("%d",&n)&&n){
        init();
        kru();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值