// B - 畅通工程续 dijkstra算法

http://acm.sdut.edu.cn:8080/vjudge/contest/view.action?cid=76#problem/B

 

// B - 畅通工程续  dijkstra算法
#include <stdio.h>
#include <string.h>
#include <math.h>
#define INF 1<<20
int map[201][201];
int dis[201];
int vis[201];
int n,m,s,t;
void dijkstra(int x)
{
    int i,j;
    memset(vis,0,sizeof(vis));
    for(i = 0;i<=n;i++)
    {
        dis[i] = map[x][i];
    }
    vis[x] = 1;
    dis[x] = 0;
    int min,pos;
    for(i = 0;i<=n;i++)
    {
        min = INF;
        for(j = 0;j<=n;j++)
        {
            if(!vis[j] && dis[j]<min)
            {
                min = dis[j];
                pos = j;
            }
        }
        if(min == INF)
        break;
        vis[pos] = 1;
        for(j = 0;j<=n;j++)
        {
            if(!vis[j] && dis[j]>dis[pos] + map[pos][j])
            {
                dis[j] = dis[pos] + map[pos][j];
            }
        }
    }
    if(dis[t]>=INF)
    {
        printf("-1\n");
    }
    else
    printf("%d\n",dis[t]);
}
int main()
{
    int i,j;
    int u,v,w;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        for(i = 0;i<=n;i++)
        {
            for(j = 0;j<=n;j++)
            {
                if(i == j)
                map[i][j] = 0;
                else
                map[i][j] = INF;
            }
        }
        for(i = 1;i<=m;i++)
        {
            scanf("%d%d%d",&u,&v,&w);
            if(map[v][u]>w)
            {
                map[u][v] = map[v][u] = w;
            }
        }
        scanf("%d%d",&s,&t);
        dijkstra(s);
    }
    return 0;
}

 

posted @ 2014-07-30 16:43  HuberyQian  阅读(207)  评论(0编辑  收藏  举报