用Kruskal算法解POJ 1251 Jungle Roads代码

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

struct road{
 int x,y,price;   //price表示连接 x,y村庄的公路维修费用 
};
int cmp(road a,road b){
 return a.price<b.price;
}
int deal(int n){
 int i,j,k=0,q,p,root[27],js=1,total=0;    //k--总边数  q--每一行边数  p--费用  root[]表示根 total--最少费用 
 road s[80];
 char a,b;    //a--x, b--y 
 
 
 for(i=0;i<n-1;i++){    
  
  scanf("\n%c %d ",&a,&q);
  for(j=0;j<q;j++){
   scanf("%c %d ",&b,&p);
   s[k].x=a-'A', s[k].y=b-'A', s[k++].price=p;
   //root[b-'A']=a-'A';
  }
 }
 sort(s,s+k,cmp);   //将边数按从小到大排序 
 for(i=0;i<n;i++)   //采用Kruskal算法  每个点指向自己 
     root[i]=i; 
 
 /*for(i=0;i<k;i++)      //输出查看 
    printf("%d--%d  %d ",s[i].x,s[i].y,s[i].price);
 printf("\n");

 for(i=0;i<n;i++)
    printf("%d->%d ",i,root[i]);
    printf("\n--------------------------------\n");*/
 
 int w;
 for(i=0;i<k&&js<n;i++)
   if(root[s[i].x]!=root[s[i].y]){
      total+=s[i].price;
      root[root[s[i].y]]=root[s[i].x];   //合并两棵树 
      for(j=0;j<n;j++){     //更新祖先节点 
       w=j;
       while(root[w]!=w)
          w=root[w];
       root[j]=w;
      } 
      js++; 
   } 
 
 return total;
}
int main(){
 int n,i,t=1,z[101];
 
 //freopen("Jungle Roads.out","w",stdout);   //文件输出 
 
 scanf("%d",&n);
 while(n!=0){
  z[t++]=deal(n);   //z[t]表示每次处理后的费用 
  scanf("%d",&n);
  
 } 
 
 for(i=1;i<t;i++)
    printf("%d\n",z[i]);
    
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值