dijkstra算法模板 -- 最短路

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

 

#include <stdio.h>
#include <string.h>
#include <math.h>
#define INF 1<<20
int map[101][101];
int dis[101];
int vis[101];
int n,m;
void dijkstra(int x)
{
    int i,j;
    int min = INF;
    int pos;
    for(i = 1;i<=n;i++)
    {
        dis[i] = map[x][i];
        vis[i] = 0;
    }
    dis[x] = 0;
    vis[x] = 1;
    for(i = 1;i<=n;i++)
    {
        min = INF;
        for(j = 1;j<=n;j++)
        {
            if(!vis[j] && dis[j]<min)
            {
              pos = j;
              min = dis[j];
            }
        }
        if(INF == min)
        break;
        vis[pos] = 1;
        for(j = 1;j<=n;j++)
        {
            if(!vis[j] && dis[j]>dis[pos] + map[pos][j])
            {
                dis[j] = dis[pos] + map[pos][j];
            }
        }
    }
    printf("%d\n",dis[n]);
}
int main()
{
    int i,j;
    int u,v,w;
    while(scanf("%d%d",&n,&m),(n||m))
    {
        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[u][v]>w)
            {
                map[u][v] = map[v][u] = w;
            }
        }
        dijkstra(1);
    }
    return 0;
}

 

posted @ 2014-07-30 15:55  HuberyQian  阅读(137)  评论(0编辑  收藏  举报