首页 > 代码库 > hdu 1863 畅通project

hdu 1863 畅通project

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;

struct data
{
    int u,v;
    double w;
}e[5000];

bool cmp(data a, data b)
{
    return a.w<b.w;
}

double x[100+5],y[100+5];
int n,m,bin[5000];

int Find(int x)
{
    int s;
    for(s=x;bin[s]>=0;s=bin[s]);

    while(s!=x)
    {
        int t=bin[x];
        bin[x]=s;
        x=t;
    }
    return s;
}

void Union(int x1,int x2)
{
    int f1=Find(x1),f2=Find(x2);
    int t=bin[f1]+bin[f2];
    if(bin[f1]>bin[f2])
    {
        bin[f1]=f2;
        bin[f2]=t;
    }
    else
    {
        bin[f2]=f1;
        bin[f1]=t;
    }

}

int main()
{
    int i,j,cas=0,num,u,v;
    double t,sum;
    while(~scanf("%d%d",&n,&m))
    {
        if(n==0) break;
        for(i=0;i<=m;i++)
            bin[i]=-1;
        for(i=0;i<n;i++)
            {
                scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
            }
        sort(e,e+n,cmp);
        sum=0;
        num=0;
        for(i=0;i<n;i++)
        {
            u=e[i].u;
            v=e[i].v;
            if(Find(u)!=Find(v))
            {
                sum+=e[i].w;
                Union(u,v);
                num++;
            }
            if(num>=m-1) break;
        }
        if(num>=m-1) printf("%d\n",sum);
        else printf("?

\n"); } return 0; }

<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

hdu 1863 畅通project