ZOJ 1372 题解

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define INT_MAX 2500

typedef struct
{
    int x, y;
    int w;
}edge;
edge e[INT_MAX];

int rank[INT_MAX], father[INT_MAX], dis_sum;

int cmp(const void *a,const void *b)
{
  return (*(edge*)a).w > (*(edge*)b).w ? 1 : -1;
}

int Exchage(int n)
{
  int i, temp;
  for(i=0; i<n; i++)
  {
    if(e[i].x > e[i].y)
    {
      temp = e[i].y;
      e[i].y = e[i].x;
      e[i].x = temp;
    }
  }
}

int Make_set(int x)
{
    father[x] = x;
    rank[x] = 0;
}

int Find_set(int x)
{
   if (x != father[x])
     father[x] = Find_set(father[x]);
   return father[x];
}

int Link(int x,int y,int w)
{
   if(rank[x] > rank[y])
   {
     father[y] = x;
   }
   else
   {
     father[x] = y;
     if(rank[x] == rank[y]) rank[y]++;
   }
   dis_sum += w;

int Kruskal(int point_amou,int edge_amou)
{
    int i, x, y;
    Exchage(edge_amou);
    for(i=0; i<point_amou; i++)
    {
       Make_set(i);
    }
    qsort(e,edge_amou,sizeof(edge),cmp);
    dis_sum = 0;
    for(i=0; i<edge_amou; i++)
    {
        x = Find_set(e[i].x);
        y = Find_set(e[i].y);
        if(x != y)
          Link(x,y,e[i].w);
    }
  return dis_sum;
}  
          
int main()
{
    int i, npoints, line, x, y;
   
    while(scanf("%d", &npoints)!= EOF)
    {
       if(npoints == 0)
           break;
       else
          scanf("%d", &line);
       if(line == 0)  printf("0\n");
       if(line != 0 && npoints != 0)
       {
         for(i=0; i<line; i++)
         {
           scanf("%d %d %d",&x,&y,&e[i].w);
           e[i].x = x - 1;
           e[i].y = y - 1;
         }
         Kruskal(npoints,line);   
         printf("%d\n", Kruskal(npoints,line));
      }
    }       
    return 0;        
}         
               刚刚学了最小生成树算法,用的模版解题过得很随意,AC的感觉就是好啊!哈哈~

在此给出代码与大家共享啊!

转载于:https://www.cnblogs.com/cn19901203/archive/2011/08/13/2136977.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值