hdu 1102 Constructing Roads

刷刷水题找感觉。。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
#include<queue>
using namespace std;
int city[110];
int find(int x)
{
    if(city[x]==x)
        return x;
    return city[x]=find(city[x]);
}
struct sb
{
    int s;
    int e;
    int v;
    bool operator <(const sb&wakaka)const
    {
        return v>wakaka.v;
    }
}test;
priority_queue<sb>q;
int main()
{
    int n;
    while(scanf("%d",&n)==1)
    {
        int v;
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                cin>>v;
                if(j<i)
                {
                    test.s=i;
                    test.e=j;
                    test.v=v;
                    q.push(test);
                }
            }
        }
        for(int i=1;i<=n;i++)
        {
            city[i]=i;
        }
        int m;
        cin>>m;
        for(int i=1;i<=m;i++)
        {
            int a,b;
            cin>>a>>b;
            int f1=find(a);
            int f2=find(b);
            if(f1!=f2)
            {
                city[f1]=f2;
            }
        }
        long long ans=0;
        while(!q.empty())
        {
            sb x=q.top();
            q.pop();
            int f1=find(x.s);
            int f2=find(x.e);
            if(f1!=f2)
            {
                city[f1]=f2;
                ans=ans+x.v;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

你可能感兴趣的:(最小生成树,HDU)