您的位置:首页 > 其它

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

2017-01-05 21:19 363 查看
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: