单源最短路径 Dijkstra算法

存储方式 :向前星

基本思想:

for循环遍历判断到 i 点的ans是否大于(到当前pos 的ans加上边权值),是则替换

然后for循环找出 当前位置pos 到 i 点最小距离, 该 i 点(注意是还未确定过的)成为下一个pos。

 

洛谷 P3371

#include<stdio.h>
#include<stdlib.h>
#include<stdlib.h>
int ver[1000000],next[1000000],head[1000000],edge[1000000],tot,m,n,s;
int state[1000000];
long long ans[1000000];
void add(int x,int y,int z)
{
    ver[++tot]=y;
    edge[tot]=z;
    next[tot]=head[x];
    head[x]=tot;
}
int main()
{
  scanf("%d%d%d",&m,&n,&s);
  for(int i=1;i<=m;i++)
  {
      ans[i]=2147483647;
  }
  ans[s]=0;
  for(int i=1;i<=n;i++)
  {
      int a,b,c;
      scanf("%d%d%d",&a,&b,&c);
      add(a,b,c);
  }
  int pos=s;
  while(state[pos]==0)
  {
      long long minn=2147483647;
      state[pos]=1;
      for(int i=head[pos];i;i=next[i])
      {
          if(!state[ver[i]]&&ans[ver[i]]>ans[pos]+edge[i])
          {
              ans[ver[i]]=ans[pos]+edge[i];
          }
      }
      for(int i=1;i<=m;i++)
      {
          if(ans[i]<minn&&state[i]==0)
          {
              minn=ans[i];
              pos=i;
          }
      }
  }
  for(int i=1;i<=m;i++)
  {
      printf("%lld ",ans[i]);
  }
}
posted @ 2021-08-25 17:24  Hin5  阅读(40)  评论(0)    收藏  举报