Luo Gu problem minimum spanning tree P3366 [template]

Minimum spanning tree

Topic links: https://www.luogu.org/problem/P3366

Title Description

If that, given an undirected graph, the minimum spanning tree is obtained, if this figure is not connected, the output orz

Input Format

The first line contains two integers N, M, N represents the total FIG nodes and the M undirected edges. (N <= 5000, M <= 200000)

Next M lines contains three integers Xi, Yi, Zi, Zi expressed a length of edges connected to node No Xi, Yi

Output Format

Comprising a number of output, i.e., the minimum spanning tree and the length of each side; if the output is not connected orz FIG.

Sample input and output

Input # 1
4 5
1 2 2
1 3 2
1 4 3
2 3 4
3 4 3
Output # 1
7

Description / Tips

Constraints of time: 1000ms, 128M

Data Scale:

For 20% of the data: N <= 5, M <= 20

For 40% of the data: N <= 50, M <= 2500

For 70% of the data: N <= 500, M <= 10000

To 100% of the data: N <= 5000, M <= 200000

Sample explained:

Therefore, the minimum spanning tree of total edge weight of 2 + 2 + 3 = 7.

Ideas: Simple template minimum spanning tree problem

//
// Created by hy on 2019/7/28.
//
#include<algorithm>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <set>
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
ll father[maxn];
ll n,ans,point,m;
struct Node{
    int u,v,w;
    bool operator<(const Node other)const{
        return this->w<other.w;
    }
}node[maxn];
ll find(ll x)
{
    if(x==father[x])
        return x;
    return father[x]=find(father[x]);
}
void kru()
{
    sort(node,node+m);
    for(int i=0;i<m;i++)
    {
        int uu=find(node[i].u);
        int vv=find(node[i].v);
        if(uu==vv)
            continue;
        else
        {
            father[uu]=vv;
            ans+=node[i].w;
            point++;
            if(point==n-1)
                break;
        }

    }
}
int main()
{
    scanf("%lld%lld",&n,&m);
    for(int i=0;i<=n;i++)
        father[i]=i;
    for(int i=0;i<m;i++)
        scanf("%lld%lld%lld",&node[i].u,&node[i].v,&node[i].w);
    ans=0,point=0;
    kru();
    printf("%lld",ans);
    if(point!=n-1)
        printf("orz");
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/Vampire6/p/11260810.html