杭电 1874 畅通工程续

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1874

 

  本题最短路问题,我用的是dijkstra算法,这题不难,但是一开始以为不会遇到重边的问题,所以WA了一次!

 

#include <stdio.h>
#define MAXN 200
#define INF 100000
int mat[MAXN][MAXN];
int min[MAXN];
void Dijkstra(int n, int s)
{
    int v[MAXN], i, j, k;
    for( i = 0; i < n; i++ )
        v[i] = 0, min[i] = INF;
    for( min[s] = 0, j = 0; j < n; j++ )
    {
        for( k = -1, i = 0; i < n; i++ )
            if( (!v[i]) && ((k == -1)||(min[i] < min[k])) )
                k = i;
        for( v[k] = 1, i = 0; i < n; i++ )
            if( (!v[i]) && (min[k] + mat[k][i] < min[i]) )
                 min[i] = min[k] + mat[k][i];
        
    }
}
int main()
{
    int n, m, i, j, k, s, t, temp;
    while(scanf( "%d%d", &n,&m ) != EOF)
    {
        for( i = 0; i < n; i++ )
            for( j = 0; j < n; j++ )
                mat[i][j] = INF;
        /*for( i = 0; i < n; i++ )
        {
            for( j = 0; j < n; j++ )
                printf("%d ",mat[i][j]);
            printf("\n");
        }
        printf("\n\n");*/        for( k = 0; k < m; k++ )
        {
            scanf( "%d%d%d", &i, &j, &temp );
            if( temp < mat[i][j] )
                mat[j][i] = mat[i][j] = temp;
        }
        /*for( i = 0; i < n; i++ )
        {
            for( j = 0; j < n; j++ )
                printf("%d ",mat[i][j]);
            printf("\n");
        }*/
        scanf( "%d%d", &s, &t );
        Dijkstra(n,s);
        /*for( i = 0; i < n; i++ )
        {
            printf("%d ",min[i]);
        }
        printf( "\n" );
        for( i = 0; i < n; i++ )
        {
            printf("%d ",pre[i]);
        }
        printf( "\n" );*/
        if( min[t] == INF )
            printf( "-1\n" );
        else
            printf("%d\n",min[t]);

    }
    return 0;
}
View Code

 

posted @ 2013-07-30 14:38  翼展zjz  阅读(137)  评论(0编辑  收藏  举报