SPFA+优先队列优化模板+输出路径

一个spfa的讲解:
https://blog.csdn.net/xunalove/article/details/70045815
题目:
poj2457
我是题目

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<vector>
using namespace std;
typedef long long ll;
const int maxn = 500005;
const int inf = 0x3f3f3f3f;
struct node
{
    int end;
    int weight;
    node(int e,int w)
    {
        this->end = e;
        this->weight = w;
    }
};
int n, m;
ll dis[maxn];
vector<node> edge[maxn];
int prev[maxn];
void spfa()
{
    fill(dis, dis + maxn, inf);
    fill(prev,prev+maxn,-1);
    priority_queue<int, vector<int>, greater<int> > q;
    q.push(1);
    dis[1] = 0;
    while(!q.empty())
    {
        int tmp = q.top();
        q.pop();
        for(int i = 0; i < edge[tmp].size(); i ++)
        {
            int nowEnd = edge[tmp][i].end;
            int nowWeight = edge[tmp][i].weight;
            if(dis[nowEnd] > dis[tmp] + nowWeight)
            {
                dis[nowEnd] = dis[tmp] + nowWeight;
                prev[nowEnd]=tmp;
                q.push(nowEnd);
            }
        }
    }
}
vector<int> get_path(int t)
{
    vector<int> path;
    for( ; t!=-1; t=prev[t])
        path.push_back(t);
    reverse(path.begin(),path.end());
    return path;
}
int main()
{
    cin >> m>>n;
    int t1,t2;
    for(int i = 1; i <= m; i ++)
    {
        scanf("%d%d",&t1,&t2);
        edge[t1].push_back(node(t2,1));
    }
    spfa();
    vector<int>ppath;
    ppath.clear();
    ppath=get_path(n);
    if(dis[n] != inf)
    {
        cout << dis[n]+1 << endl;
        for(int i=0; i<ppath.size(); i++)
        {
            printf("%d\n",ppath[i]);
        }
    }
    else
        cout << "-1" << endl;
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值