标签:
最短路问题 HDU2544:
1.解决无负权边的带权有向图或无向图的单源最短路问题
#include<stdio.h>#include<string.h>
# define N 110
# define INF 0xfffffff
# define Min(a, b) (a < b ? a : b)
int G[N][N];
int dist[N];
int vis[N];
int n, m;
void Start()
{
int i, j;
memset(vis, 0, sizeof(vis));
for (i = 1; i <= n; i++)
{
dist[i] = INF;
for (j = 1; j <= n; j++)
G[i][j] = INF;
}
}
void Dij()
{
int i, j, idex, M;
dist[1] = 0;
for (i = 1; i <= n; i++)
{
M = INF;
for (j = 1; j <= n; j++)
{
if (vis[j] == 0 && dist[j] < M)
{
M = dist[j];
idex = j;
}
}
vis[idex] = 1; //每次找到最小的就置为1
for (j = 1; j <= n; j++)
{
if (vis[j] == 0 && (dist[j] > dist[idex] + G[idex][j]))
{
dist[j] = dist[idex] + G[idex][j]; //将每个首位到 j 的最短距离记录下来
}
}
}
}
int main ()
{
int i, a, b, c;
while (scanf("%d %d", &n, &m), n+m)
{
Start();
for (i = 0; i < m; i++)
{
scanf("%d %d %d", &a, &b, &c);
G[a][b] = Min(G[a][b], c);
G[b][a] = G[a][b];
}
Dij();
printf("%d\n", dist[n]);
}
return 0;
}
2. 每一对顶点之间的最短路径
#include<stdio.h>
#include<string.h>
# define N 110
# define INF 0xfffffff
# define Min(a, b) (a < b ? a : b)
int G[N][N];
int n, m;
void Start()
{
int i, j;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
G[i][j] = INF;
}
}
void Dij()
{
int i, j, k;
for (k = 1; k <= n; k++)
{
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
G[i][j] = Min(G[i][k]+G[k][j], G[i][j]);
}
}
}
}
int main ()
{
int i, a, b, c;
while (scanf("%d %d", &n, &m), n+m)
{
Start();
for (i = 0; i < m; i++)
{
scanf("%d %d %d", &a, &b, &c);
G[a][b] = Min(G[a][b], c);
G[b][a] = G[a][b];
}
Dij();
printf("%d\n", G[1][n]);
}
return 0;
}
标签:
原文地址:http://www.cnblogs.com/syhandll/p/4437795.html