Sicily 1083 Networking

1317 단어
최소 스패닝 트리
#include <stdio.h>
const int maxl=110;
int main()
{
    int n,r,i,j,k,sum,d,ctr;
    int data[100][100];

    scanf( "%d",&n );
    while ( n!=0 ) {
        for ( i=0;i<=n;i++ )
            for ( j=0;j<=n;j++ )
                data[i][j]=maxl;
        scanf( "%d",&r );
        for ( k=0;k<r;k++ ) {
            scanf( "%d%d%d",&i,&j,&d );
            if ( data[i-1][j-1]>d ) {
                data[i-1][j-1]=d;
                data[j-1][i-1]=d;
            }
        }
        ctr=0;
        sum=0;
        while ( ctr<n-1 ) {
            k=maxl;
            for ( i=1;i<n;i++ ) {
                if ( data[0][i]<k ) {
                    k=data[0][i];
                    j=i;
                }
            }
            sum+=k;
            ctr++;
            for ( i=1;i<n;i++ ) {
                if( data[j][i]<data[0][i] ) 
                    data[0][i]=data[j][i];
                if ( data[i][j]<data[i][0] )
                    data[i][0]=data[i][j];
                data[i][j]=maxl;
                data[j][i]=maxl;
            }
            data[0][j]=maxl;
            
        }
        printf( "%d
",sum ); scanf( "%d",&n ); } return 0; }

좋은 웹페이지 즐겨찾기