Floyd 算法 --最短路算法之二

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]);
}
*/
void floyd(int n)
{
    int i,j,k;
    for(k = 0;k<=n;k++)
    {
        for(i = 0;i<=n;i++)
        {
            for(j = 0;j<=n;j++)
            {
                if(map[i][j]>map[i][k] + map[k][j])
                map[i][j] = map[i][k] + map[k][j];
            }
        }
    }
}
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;
            }
        }
        floyd(n);
        printf("%d\n",map[1][n]);
        //dijkstra(1);
    }
    return 0;
}

 

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