1. 程式人生 > >spfa模版

spfa模版

fir else node gin back long clu div name

#include<bits/stdc++.h>

using namespace std;

int n,m;//點邊
int beginn;

int u[500005],v[500005],w[500005];
int first[500005],nextt[500005]; 

long long dis[500005];
int book[500005];

int k2=0;

void clean()
{
    for(int i=1;i<=n;i++)
    {
        dis[i]=2147483647;
        if(i==beginn) dis[i]=0;
        
        first[i]
=-1; } for(int i=1;i<=m;i++) { nextt[i]=-1; } } void make_edge(int _a,int _b,int _c) { k2++; u[k2]=_a; v[k2]=_b; w[k2]=_c; nextt[k2]=first[u[k2]]; first[u[k2]]=k2; } deque<int> q; int main() { cin>>n>>m>>beginn; clean();
for(int i=1;i<=m;i++) { int a,b,c; cin>>a>>b>>c; make_edge(a,b,c); } book[beginn]=1; q.push_front(beginn); while(!q.empty()) { int now_node=q.front(); book[now_node]=0; q.pop_front();
int k=first[u[now_node]]; while(k!=-1) { if(dis[v[k]]>dis[u[k]]+w[k]) { dis[v[k]]=dis[u[k]]+w[k]; if(book[v[k]]==0) { book[v[k]]=1; if(!q.empty()&&dis[v[k]]<dis[q.front()]) { q.push_front(v[k]); } else q.push_back(v[k]); } } k=nextt[k]; } } for(int i=1;i<=n;i++) { if(i==beginn) cout<<"0 "; else cout<<dis[i]<<" "; } cout<<endl; return 0; }

spfa未調過

spfa模版