最小生成树二·Kruscal算法

描述

随着小Hi拥有城市数目的增加,在之间所使用的Prim算法已经无法继续使用了——但是幸运的是,经过计算机的分析,小Hi已经筛选出了一些比较适合建造道路的路线,这个数量并没有特别的大。

所以问题变成了——小Hi现在手上拥有N座城市,且已知其中一些城市间建造道路的费用,小Hi希望知道,最少花费多少就可以使得任意两座城市都可以通过所建造的道路互相到达(假设有A、B、C三座城市,只需要在AB之间和BC之间建造道路,那么AC之间也是可以通过这两条道路连通的)。

提示:积累的好处在于可以可以随时从自己的知识库中提取想要的!

输入

每个测试点(输入文件)有且仅有一组测试数据。

在一组测试数据中:

第1行为2个整数N、M,表示小Hi拥有的城市数量和小Hi筛选出路线的条数。

接下来的M行,每行描述一条路线,其中第i行为3个整数N1_i, N2_i, V_i,分别表示这条路线的两个端点和在这条路线上建造道路的费用。

对于100%的数据,满足N<=10^5, M<=10^6,于任意i满足1<=N1_i, N2_i<=N, N1_i≠N2_i, 1<=V_i<=10^3.

对于100%的数据,满足一定存在一种方案,使得任意两座城市都可以互相到达。

输出

对于每组测试数据,输出1个整数Ans,表示为了使任意两座城市都可以通过所建造的道路互相到达至少需要的建造费用。

Sample Input

5 29
1 2 674
2 3 249
3 4 672
4 5 933
1 2 788
3 4 147
2 4 504
3 4 38
1 3 65
3 5 6
1 5 865
1 3 590
1 4 682
2 4 227
2 4 636
1 4 312
1 3 143
2 5 158
2 3 516
3 5 102
1 5 605
1 4 99
4 5 224
2 4 198
3 5 894
1 5 845
3 4 7
2 4 14
1 4 185

Sample Output

92
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<math.h>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int maxx=1e5+5;
int n,m;
int par[maxx];

struct edge
{
    int u;
    int v;
    int cost;
};
edge es[1000005];

void init(int n)
{
    for(int i=0;i<n;i++)
        par[i]=i;
}

int seek(int x)
{
    if(x==par[x])
        return x;
    else
        return par[x]=seek(par[x]);
}

void unite(int x,int y)
{
    int xx=seek(x);
    int yy=seek(y);
    if(xx!=yy)
        par[xx]=yy;
}

bool same(int x,int y)
{
    int xx=seek(x);
    int yy=seek(y);
    return (xx==yy);
}

bool cmp(edge e1,edge e2)
{
    return e1.cost<e2.cost;
}

int Kruskal()///Kruskal算法,时间复杂度O(mlogn),代码复杂,更适用于点多,无法用矩阵存边的情况,
{
    sort(es,es+m,cmp);
    init(n);
    int res=0;
    for(int i=0;i<m;i++)
    {
        edge e=es[i];
        if( !same(es[i].u, es[i].v) )///利用并查集判断点是否在生成树内
        {
            res+=es[i].cost;
            unite(es[i].u, es[i].v);
        }
    }
    return res;
}


int main()
{
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        for(int i=0;i<m;i++)
            scanf("%d%d%d",&es[i].u, &es[i].v, &es[i].cost);
        int ans=Kruskal();
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/shoulinniao/p/10328511.html
今日推荐