迪杰斯特拉算法入门题。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
int min(int a,int b)
{
if(a>b) return b;
return a;
}
int max(int a,int b)
{
if(a>=b) return a;
return b;
}
int main()
{
int n,m,t;
int i,j,k;
int dist[310][310];
int a,b,c;
int x,y;
memset(dist,-1,sizeof(dist));
scanf("%d%d%d",&n,&m,&t);
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&a,&b,&c);
dist[a][b]=c;
}
for(i=1;i<=n;i++)
dist[i][i]=0;
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
if(i==k)
continue;
for(j=1;j<=n;j++)
{
if(i==k||j==k)
continue;
if(dist[i][k]==-1||dist[k][j]==-1)
continue;
if(dist[i][j]!=-1)
{
dist[i][j]=min(dist[i][j],
max(dist[i][k],dist[k][j]));
}
else
{
dist[i][j]=max(dist[i][k],dist[k][j]);
}
}
}
}
for(i=1;i<=t;i++)
{
scanf("%d%d",&x,&y);
printf("%d\n",dist[x][y]);
}
return 0;
}
本文介绍了一道迪杰斯特拉算法的经典入门题目,并通过C语言实现了解决方案。该程序利用了Floyd算法进行路径优化,实现了节点间的最短路径计算。
159

被折叠的 条评论
为什么被折叠?



