hdu 2544 最短路(两点间最短路径)

题目:http://acm.hdu.edu.cn/showproblem.php?pid=2544

方法一:dijkstra算法,求两点之间最短路径。

/************************************************************************/
/*     
        hdu  最短路
        两点之间最短路径
        题目大意:dijkstra求两点之间最短路径。
*/
/************************************************************************/

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>

#define MAX 0xfffffff

const int N = 101;
int map[N][N];
int vis[N];
int dj[N];
int num,m,n;

void build_map()
{
    int a,b,c;
    for (int i = 1; i <= n; i++)
    for (int j = i; j <= n; j++)
    map[i][j] = map[j][i] = (i==j)?0:MAX;
    for (int i = 0; i < m; i++)
    {
        scanf("%d%d%d",&a,&b,&c);
        map[a][b] = map[b][a] = c;
    }

}

int DJ()
{
    int t = n;
    int sum = 0;
    int min,k;
    for (int i = 1; i <= n; i++)
    dj[i] = MAX;
    int cur = 1;
    dj[cur] = 0;
    while(1)
    {
        min = MAX;
        vis[cur] = 1;
        for (int i = 1; i <= n; i++)
        {
            if(vis[i]==1)continue;
            if(dj[i]>map[i][cur]+dj[cur])
                dj[i] = map[i][cur]+dj[cur];
            if (dj[i]<min)
            {
                min = dj[i];
                k = i;
            }
        }
        cur = k;
        if(k==n)break;
    }
    
    return dj[n];
}


int main()
{
    
    while(scanf("%d%d",&n,&m) && (n!=0 && m!=0) )
    {
        build_map();
        memset(vis,0,sizeof(vis));
        printf("%d\n",DJ());
    }
    return 0;
}

方法二:floyd算法,求两点之间最短距离, distance[i][j] = min(distance[i][j], distance[i][k]+distance[k][j]);借助中间点。

/************************************************************************/
/*     
        hdu  最短路
        两点之间最短路径
        题目大意:floyd算法,求得两点之间最短距离,(u,v) = min( (u,v),(v,w)+(w,v) );
*/
/************************************************************************/

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>

#define MIN(a,b) a<b?a:b
#define MAX 0xfffffff

const int N = 101;
int map[N][N];
int vis[N];
int dj[N];
int num,m,n;

void build_map()
{
    int a,b,c;
    for (int i = 1; i <= n; i++)
    for (int j = i; j <= n; j++)
    map[i][j] = map[j][i] = (i==j)?0:MAX;
    for (int i = 0; i < m; i++)
    {
        scanf("%d%d%d",&a,&b,&c);
        map[a][b] = map[b][a] = c;
    }

}

int floyd()
{
    for (int k = 1; k <= n; k++)
    {
        for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
        map[i][j] = MIN(map[i][j],map[i][k] + map[k][j]);
    }
    return map[1][n];
}


int main()
{
    
    while(scanf("%d%d",&n,&m) && (n!=0 && m!=0) )
    {
        build_map();
        memset(vis,0,sizeof(vis));
        printf("%d\n",floyd());
    }
    return 0;
}

 

posted on 2013-08-12 19:52  NewPanderKing  阅读(734)  评论(0编辑  收藏  举报

导航