最短路径——SPFA算法(C++)

源代码:

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
queue <int> h;
int i[1001][1001],j[1001],n,k; //要想节省空间,会不会有更好的方法呢?
bool f[1001]={0};
int main()
{
    memset(i,0x3f,sizeof(i));
    memset(j,0x3f,sizeof(j));
    scanf("%d%d",&n,&k);
    for (int a=1;a<=n;a++)
      for (int b=1;b<=n;b++)
      {
        int t;
        scanf("%d",&t);
        if (t!=-1)
          i[a][b]=t;
      } //矩阵输入。
    j[k]=0;
    f[k]=true;
    h.push(k);
    while (h.size())
    {
      int t=h.front();
      for (int a=1;a<=n;a++)
        if (i[t][a]+j[t]<j[a])
        {
          j[a]=i[t][a]+j[t];
          if (!f[a])
          {
            f[a]=true;
            h.push(a);
          }
        }
      h.pop();
f[t]=false; }
//利用队列除去冗余运算,从而进行显著的优化。 for (int a=1;a<=n;a++) printf("%d ",j[a]); return 0; }
原文地址:https://www.cnblogs.com/koruko/p/5182338.html