您的位置:首页 > 其它

poj 1251 丛林中的路 最小生成树问题 克鲁斯卡方法 并查集解决

2014-03-07 19:22 561 查看
题目链接:http://bailian.openjudge.cn/practice/1251/

这是一个让我蛋疼不已的程序,核心算法倒是不难,很快就写完了。说到底还是学渣基础知识太差,居然在scanf字符输入上栽了!!!!!scanf函数对字符的识别是比较傻瓜的因为空格 回车等都会当做字符出理所以写字符输入时要特别注意自己规避错误。

说道最小生成树问题运用克鲁斯卡方法并辅以并查集还是很简单的,将边的权值做以下快排让后就是并查集的事了,如果理解并查集和克鲁斯卡方法这个程序就很简单了。

#include <stdio.h>
#include <algorithm>
using namespace std;

int tree[28];
int findroot(int x){
if(tree[x]==-1)
return x;
else{
int tmp=findroot(tree[x]);
tree[x]=tmp;
return tmp;
}
}

struct Edge{
int a,b;
int cost;
bool operator < (const Edge &A) const{
return cost<A.cost;
}
}edge[76];

int main(){
int n;
while(scanf("%d", &n)!=EOF && n!=0){
char head;
char tail;
int cost;
int m;
int size=0;
int n_=n-1;
while(n_--){
scanf(" %c %d",&head,&m); //注意字符输入问题,回车键也会被当成一个字符,所以%c前要加一个空格
while(m--){
scanf(" %c %d",&tail,&cost);
edge[size].a=(int)(head-'A');
edge[size].b=(int)(tail-'A');
edge[size].cost=cost;
size++;
}
}
sort(edge,edge+size);
for(int i=0;i<n;i++){
tree[i]=-1;
}
int ans=0;
for(int i=0;i<size;i++){
int a=findroot(edge[i].a);
int b=findroot(edge[i].b);
if(a!=b){
tree[a]=b;
ans+=edge[i].cost;
}
}
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: