并查集水题

市政府“惠民工程”的目标是在全市n个居民点间之架设煤气管道(但不一定有直接的管道相连,只要能间接通过管道可达即可)。很显然最多可架设 n(n-1)/2条管道,然而实际上要连通n个居民点只需架设n-1条管道就可以了。现请你编写程序,计算出该惠民工程需要的最低成本。

Input

测试输入包含若干测试用例。每个测试用例的第1行给出居民点数目M ( < =100 )、 评估的管道条数 N;随后的 N 行对应居民点间管道的成本,每行给出一对正整数,分别是两个居民点的编号,以及此两居民点间管道的成本(也是正整数)。为简单起见,居民点从1到M编号。

Output

对每个测试用例,在1行里输出全市管道畅通所需要的最低成本。若统计数据不足以保证畅通,则输出“?”。

Sample Input
3 3
1 2 1
1 3 2
2 3 4
3 1
2 3 2
Sample Output
3
?



#include <vector>
#include <iostream>
#include <string>
#include <map>
#include <stack>
#include <cstring>
#include <queue>
#include <list>
#include <cstdio>
#include <set>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include <cctype>
#include <sstream>
#include <functional>
using namespace std;


#define LL long long
#define INF 1E4 * 1E9
#define pi acos(-1)
#define endl '\n'
#define me(x) memset(x,0,sizeof(x));
const int maxn=1e4+5;
const int maxx=1e7+5;
//
//找一次树高会减少
struct node
{
    int u,v,c;
}q[maxn];
int n,m;
bool cmp(node a,node b)
{
    return a.c<b.c;
}
int fa[maxn];


int fi(int x)
{
    return fa[x]==x?x:fi(fa[x]);
}
int check(int x,int y)
{
    int p1=fi(x),p2=fi(y);
    if(x==y) return 1;
    else return 0;
}
int main()
{
    while(cin>>n>>m)
    {
        for(int i=1;i<=m;i++)
            cin>>q[i].u>>q[i].v>>q[i].c;
        sort(q+1,q+m+1,cmp);
        for(int i=1;i<=n;i++)
            fa[i]=i;
        int cur=1,cos=0;
        for(int i=1;i<=m;i++)
        {
            int fx=fi(q[i].u),fy=fi(q[i].v);
            if(fx!=fy)
            {
                fa[fx]=fy;
                cur++;
                cos+=q[i].c;

            }
        }
        if(cur==n) cout<<cos<<endl;
        else cout<<"?"<<endl;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值