SPFA模板

SPFA算法模板解析与应用
#include<iostream>
#include<cstdio>
#include<string.h>
#include<cstring>
#include<string>
#include<stack>
#include<set>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#include<queue>

#define LOCAL
#define ll long long
#define lll unsigned long long
#define MAX 1000009
#define eps 1e-8
#define INF 0x7fffffff
#define mod 1000000007

using namespace std;
/*

题意:最短路

想法:SPFA算法模板

*/
struct Arcnode//邻接表
{
    int to;
    int weight;
    Arcnode *next;
};
queue<int>Q;//存储顶点
int n;
Arcnode* List[1009];//每个顶点的链表的头指针
int dist[1009];//源点到每个顶点的距离
int path[1009];//路径
int vis[1009];//判断该点是否在队列中
int shortest[1009];//存储路径

void SPFA(int x)
{
    Arcnode* temp;
    for(int i = 0;i<n;i++)//初始化
    {
        dist[i] = INF;
        path[i] = x;
        vis[i] = 0;
    }
    dist[x] = 0;
    path[x] = x;
    vis[x]++;
    Q.push(x);
    while(!Q.empty())//松弛操作
    {
        int u = Q.front();
        Q.pop();
        vis[u]--;
        temp = List[u];
        while(temp!=NULL)
        {
              int v = temp->to;//取出u下面的节点v
              if(dist[v]>dist[u] + temp->weight)
              {
                  dist[v] = dist[u] + temp->weight;
                  path[v] = u;
                  if(!vis[u])
                  {
                      Q.push(v);
                      vis[v]++;
                  }
              }
              temp = temp->next;
        }
    }
}
int main()
{
    //#ifdef LOCAL
    //freopen("date.in","r",stdin);
       //freopen("date.out","w",stdout);
    //#endif // LOCAL
    int u,v,w;
    scanf("%d",&n);
    Arcnode* temp;
    while(1)
    {
        scanf("%d%d%d",&u,&v,&w);
        if(u==-1&&v==-1&&w==-1)break;
         temp = new Arcnode;
         temp->to = v; temp->weight = w; temp->next = NULL;
         if(List[u]==NULL) List[u] = temp;
         else
         {
             temp->next = List[u];
             List[u] = temp;
         }
    }
    SPFA(0);
    for(int j = 0;j<n;j++)//一定要释放空间
    {
        temp = List[j];
        while(temp!=NULL)
        {
            List[j] = temp->next;
            delete temp;
            temp = List[j];
        }
    }
    for(int i = 1;i<n;i++)
    {
        printf("%d ",dist[i]);
        memset(shortest,0,sizeof(shortest));
        int k = 0;
        shortest[k] = i;
        while(path[shortest[k]]!=0)
        {
            k++;
            shortest[k] = path[shortest[k - 1]];
        }
        k++;
        shortest[k] = 0;
        for(int j = k;j>0;j--)
        {
            printf("%d->",shortest[j]);
        }
        printf("%d\n",shortest[0]);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值