Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

最大生成树,并查集,1次AC纪念,呵呵

Posted by 1083595345 at 2015-07-16 19:41:59 on Problem 2377
简单的水题,,,
#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;

const int maxn=1000000;

struct edge
{
    int fr,to,cost;
};

edge Ed[maxn];
int V[maxn];

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

int find(int x)
{
    if(x!=V[x])
        V[x]=find(V[x]);
    return V[x];
}

void unite(int x,int y)
{
    int f1=find(x);
    int f2=find(y);
    V[f1]=f2;
}

int main()
{
    int v,e;
    scanf("%d%d",&v,&e);
    for(int i=0;i<e;i++)
    {
        edge ed;
        scanf("%d%d%d",&ed.fr,&ed.to,&ed.cost);
        Ed[i]=ed;
    }
    sort(Ed,Ed+e,cmp);
    for(int i=1;i<=v;i++)
        V[i]=i;
    int ans=0;
    int num=1;
    for(int i=0;i<e;i++)
    {
        edge ed=Ed[i];
        if(find(ed.fr)!=find(ed.to))
        {
            unite(ed.fr,ed.to);
            ans+=ed.cost;
            num++;
        }
    }
    num==v?printf("%d\n",ans):printf("-1\n");

    return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator