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;
}
这是一个让我蛋疼不已的程序,核心算法倒是不难,很快就写完了。说到底还是学渣基础知识太差,居然在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;
}
相关文章推荐
- POJ - 1251 Jungle Roads (最小生成树Kruskal、并查集)
- POJ1251—最小生成树问题的Prim实现
- POJ 1789 Truck History (prim解决最小生成树问题)
- ZOJ 1406 POJ 1251 Jungle Roads 丛林中的道路,最小生成树,Kruskal算法
- poj 1251 最小生成树问题
- [置顶] 并查集解决最优灌溉问题(最小生成树问题)
- 使用jQuery的插件qrcode生成二维码(静态+动态生成)及常见问题解决方法
- 多线程中生成随机数序列重复问题的解决方法
- jsp获取JavaScript生成的中文cookie出现乱码问题解决方法
- Eclipse build Android时不生成apk问题解决方法
- 利用Ecipse生成Javadoc乱码(编码问题)终极解决方法
- poj 1251 Jungle Roads(最小生成树)
- NetcfSvcUtil生成的WCF代理类保存数字类型到Server端总为0问题解决方法
- POJ 1251 Jungle Roads(最小生成树水题) - from lanshui_Yang
- poj 1251 Jungle Roads(最小生成树)
- POJ 1251 Jungle Roads 最小生成树
- DEDECMS 自动缩略图无法生成问题的解决方法
- POJ-1251 HDU-1301 (最小生成树)
- 利用jasperreports报表生成pdf文档中文不能显示问题解决方法
- POJ 1287 Networking(并查集,最小生成树)