1. 程式人生 > >SPFA+優先佇列優化模板+輸出路徑

SPFA+優先佇列優化模板+輸出路徑

#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;
}