spfa模版

#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未调过

posted @ 2018-12-14 15:10  前排吃瓜  阅读(125)  评论(0编辑  收藏  举报