poj 1251 郁闷了,大爷的、、、、、

本文介绍了一个基于最小生成树算法的实现案例,通过使用C++编程语言来解决特定问题。该程序利用了结构体、排序和并查集等数据结构与算法,实现了对城市间连接成本的最小化计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstring>

using namespace std;
typedef struct rode
 {
       int c1, c2, cost;
 }rode;
int S[100];
rode city[100];
int find(int x)
{
     if(S[x]==-1) return x;
     return S[x]==find(S[x]);   
}
int compare(const rode &a, const rode &b)
{
 
   if(a.cost < b.cost)
       return 1;
       return 0;
}

bool marge(int x, int y)
{
    int m = find(x);
    int n = find(y);
    if(m == n) return 0;
    if(m<n)   S[x] = y;
    else S[y] = x;
    return 1;
}
int main()
{
    int N;
    char c;
    int number, W;
    int t, sum;
    while(scanf("%d",&N)&&N)
    {   t =0;  sum =0;
          getchar();
        for(int i=0; i<N-1; i++)
        {
        scanf("%c %d",&c, &number);
         t+=number;
        for(int j=0; j<number; j++)
        {
        scanf(" %c %d",&c,&W);
        city[i].c1 = i;
        city[i].c2 = j-'A';
        city[i].cost = W;
        }
        getchar();
        }
        memset(S, -1, sizeof(S));
        sort(city,city+t,compare);
      for(int i=0; i<t; i++)
      if(marge(city[i].c1, city[i].c2))
      {
          sum+=city[i].cost;
      }
      printf("%d\n",sum);
    }
   system("pause");
   return 0;
}
题目 点击打开链接
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值