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

时间:2021-08-13 09:40:50

题目: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 = ;
int map[N][N];
int vis[N];
int dj[N];
int num,m,n; void build_map()
{
int a,b,c;
for (int i = ; i <= n; i++)
for (int j = i; j <= n; j++)
map[i][j] = map[j][i] = (i==j)?:MAX;
for (int i = ; i < m; i++)
{
scanf("%d%d%d",&a,&b,&c);
map[a][b] = map[b][a] = c;
} } int DJ()
{
int t = n;
int sum = ;
int min,k;
for (int i = ; i <= n; i++)
dj[i] = MAX;
int cur = ;
dj[cur] = ;
while()
{
min = MAX;
vis[cur] = ;
for (int i = ; i <= n; i++)
{
if(vis[i]==)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!= && m!=) )
{
build_map();
memset(vis,,sizeof(vis));
printf("%d\n",DJ());
}
return ;
}

方法二: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 = ;
int map[N][N];
int vis[N];
int dj[N];
int num,m,n; void build_map()
{
int a,b,c;
for (int i = ; i <= n; i++)
for (int j = i; j <= n; j++)
map[i][j] = map[j][i] = (i==j)?:MAX;
for (int i = ; i < m; i++)
{
scanf("%d%d%d",&a,&b,&c);
map[a][b] = map[b][a] = c;
} } int floyd()
{
for (int k = ; k <= n; k++)
{
for (int i = ; i <= n; i++)
for (int j = ; j <= n; j++)
map[i][j] = MIN(map[i][j],map[i][k] + map[k][j]);
}
return map[][n];
} int main()
{ while(scanf("%d%d",&n,&m) && (n!= && m!=) )
{
build_map();
memset(vis,,sizeof(vis));
printf("%d\n",floyd());
}
return ;
}