1285: Vegetable and Road again

1285: Vegetable and Road again [最小生成树]

时间限制: 1 Sec  内存限制: 128 MB

题目描述

修路的方案终于确定了。市政府要求任意两个公园之间都必须实现公路交通(并不一定有直接公路连接,间接公路相连也可以)。但是考虑到经济成本,市政府希望钱花的越少越好。

你能帮助Vegetable找到给出的修路方案所需的最少花费吗?

输入

有T组测试数据。

每组包含一组N(0<n<=100)和M,N表示有N个公园,M表示这N个公园间的M条路。

接下来给出M行,每行包括A,B, C。表示A和B之间修公路需要花费C元。

输出

若给出的方案可行,输出该方案最小需要的花费,若给出的方案不可行,输出Wrong。

样例输入

1
4 3
1 2 1
2 3 2
3 4 3

样例输出

6
思路:MST的dij模板;

#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<stack>
#include<algorithm>
#include<iostream>
using namespace std;
int pre[1010];
struct node
{
    int a;
    int b;
    int c;
}s[10010];
int find(int x)
{
    if(pre[x]==x) return x;
    return pre[x]=find(pre[x]);
}
bool cmp(node x,node y)
{
    return x.c<y.c;
}
int main()
{
    int n,m,t,p1,p2;
    scanf("%d",&t);
    while(t--)
    {
        for(int i=1;i<=1010;i++)
            pre[i]=i;
        scanf("%d %d",&n,&m);
        int v;
        int p=0;
        while(m--)
        {
            scanf("%d %d %d",&p1,&p2,&v);
            s[p].a=p1;
            s[p].b=p2;
            s[p].c=v;
            p++;
        }
        int num=0,ans=0;
        sort(s,s+p,cmp);
        for(int i=0;i<p && num<n-1;i++)
        {
            int fx=find(s[i].a);
            int fy=find(s[i].b);
            if(fx!=fy)
            {
                pre[fy]=fx;
                num++;
                ans+=s[i].c;
            }
        }
        if(num==n-1)
            printf("%d\n",ans);
        else printf("Wrong\n");
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值