Sicily1083. Networking

最小生成树问题

// Problem#: 1083
// Submission#: 1167864
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include<iostream>
#include<cstring>
using namespace std;

int a[55][55];
int visited[55];
int d[55];
const int Max=1000000;

int main()
{
    int place,road;
    int sta,end,len;
    while(cin>>place,place)
    {
        cin>>road;
        int result=0;
        memset(a,Max,sizeof(a));
        memset(visited,0,sizeof(visited));
        memset(d,Max,sizeof(d));
        for(int i=0;i<road;i++)
        {
            cin>>sta>>end>>len;
            if(len < a[sta][end])
                a[sta][end]=a[end][sta]=len;
        }
        int v=1;
        visited[v]=1;
        d[v]=0;
        for(int i=1;i<=place;i++)
        {
            if(i!=1)
                d[i]=a[v][i];
        }
        for(int i=1;i<=place;i++)
        {
            int min=Max;
            for(int i=1;i<=place;i++)
                if(!visited[i]&&d[i]<min)
                {
                    v=i;
                    min=d[i];
                }
            result += min;
            visited[v]=1;
            for(int i=1;i<=place;i++)
                if(!visited[i]&&d[i]>a[v][i])
                    d[i]=a[v][i];
        }
        cout<<result-1000000<<endl;
    }
    return 0;
}                                

你可能感兴趣的:(sun,networking)