Luo Gu U85154 familiar with the environment

Luo Gu U85154 familiar with the environment

Topic Portal

Topic background

Konjac * S Seaway E A w A ** * came to the y-big brother clouds of a high-class 66 (casually pulled out a test scores in excess of 620 ... qwq) he decided quickly into this new group as soon as possible began to catch up with the pace ...... bigwigs of course, the first thing he has to do is familiar with the campus environment.

Title Description

Before Seaway S E A W A Y for objects in one ulterior it has been known JDFZ J D F. The Z campus contains a N N points, M M weighted undirected graph edges. Because it is on campus, so this figure must be Unicom. Seaway S E A w A the y- naive enough to think that the longer he left the road, the more he knowledge of the campus. But idle Seaway S E A W A Y and want to go too far, he just wanted to go over each point. Now he's ready to go from a 66-class (One point on the graph) high, traveled the entire campus. Will he go long way, he traveled to the entire campus.

Input Format

The first line of the input file comprises a integer N N .

After M M rows, each row having three integers the U-, V, the Z the U- , V , the Z , represents from the U- the U- into V V has a length of the Z the Z side.

Output Format

Only one line of the output file, comprising an integer, S * represents Seaway E A W A Y ** * take the long path.

Sample input and output

Input # 1 copy

Output # 1 copy

Description / Tips

data range:

1 \ N \ 10001≤ the N ≤1000,1 \ M \ the 1000001≤ M ≤100000.

answer:

On the basis of the original drawing water problems exam T3 ...

The bare maximum spanning tree.

Code:

#include<cstdio>
#include<algorithm>
using namespace std;
int n,u,v,val,tot,ans,cnt;
int fa[1001];
struct node
{
    int x,y,z;
}e[100001];
inline bool cmp(const node &a,const node &b)
{
    return a.z>b.z;
}
int find(int x)
{
    return fa[x]==x?x:fa[x]=find(fa[x]);
}
int main()
{
    //freopen("#10.in","r",stdin);
    //freopen("#10.out","w",stdout);
    scanf("%d",&n);
    while(scanf("%d%d%d",&u,&v,&val)!=EOF)
    {
        e[++tot].x=u;
        e[tot].y=v;
        e[tot].z=val;
    }
    for(int i=1;i<=n;i++)
        fa[i]=i;
    sort(e+1,e+tot+1,cmp);
    for(int i=1;i<=tot;i++)
    {
        int fx=find(e[i].x);
        int fy=find(e[i].y);
        if(fx!=fy)
        {
            fa[fx]=fy;
            ans+=e[i].z;
            cnt++;
        }
        if(cnt==n-1)
            break;
    }
    printf("%d",ans);
    return 0;
}

Guess you like

Origin www.cnblogs.com/fusiwei/p/11402108.html