sdutacm-图结构练习——最小生成树

图结构练习——最小生成树

Time Limit: 1000MS MemoryLimit: 65536KB

SubmitStatistic

ProblemDescription

 n个城市,其中有些城市之间可以修建公路,修建不同的公路费用是不同的。现在我们想知道,最少花多少钱修公路可以将所有的城市连在一起,使在任意一城市出发,可以到达其他任意的城市。

 

Input

 输入包含多组数据,格式如下。

第一行包括两个整数n m,代表城市个数和可以修建的公路个数。(n <= 100 m <=10000)

剩下m行每行3个正整数a b c,代表城市a 和城市b之间可以修建一条公路,代价为c

 

Output

 每组输出占一行,仅输出最小花费。

ExampleInput

3 2

1 2 1

1 3 1

1 0

ExampleOutput

2

0

Hint

 

Author

 赵利强'

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int f[102000]={0},n,m,k,sum,book[102000];
struct node
{
int u,v,w;
}e[10002];
void quicksort(int l,int r)
{
    int i,j;
    node t;
    if(l>r)
    return;
    i = l;
    j = r;
    while(i!=j)
    {
        while(e[j].w>=e[l].w&&i<j)
        {
        j--;
        }
        while(e[i].w<=e[l].w&&i<j)
        {
        i++;
        }
        if(i<j)
        {
        swap(e[j],e[i]);
        }

    }
    swap(e[l],e[i]);
    quicksort(l,i-1);
    quicksort(i+1,r);
    return ;

}
int getf(int v)
{
    if(f[v]==v)
    {
        return v;
    }
    else
    {
        f[v] = getf(f[v]);
        return f[v];
    }
}
int amerge(int l,int r)
{
    int t1,t2;
    t1 = getf(l);
    t2 = getf(r);
    if(t1!=t2)
    {
        f[t2] = t1;
        return 1;
    }
    return 0;
}
int main()
{
    int x,y,i;
    while(~scanf("%d%d",&n,&m))
    {
        if(n==0)
        {
         printf("0\n");
        continue;
        }

        sum =0;
        //int nmax=0;//为图中出现的最大顶点编号
        for(i=1;i<=n;i++)
        {
            f[i] = i;

        }
        int count=0;
       // memset(book,0,sizeof(book));
        for(i=1;i<=m;i++)
        {
            scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);


        }quicksort(1,m);
       for(i=1;i<=m;i++)
       {
        if(amerge(e[i].u,e[i].v))
        {
            count++;
            sum+=e[i].w;
        }
        if(count==n-1)
        break;
       }
       printf("%d\n",sum);

    }
    return 0;
}



/***************************************************
User name: jk160505徐红博
Result: Accepted
Take time: 16ms
Take Memory: 252KB
Submit time: 2017-02-17 14:48:38
****************************************************/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值