单源最短路spfa(队列优化)

int d[maxn];bool vis[maxn];
struct Edge{
    int to,v;
};
vector<Edge>g[maxn];
void spfa(){
    deque<int>q;
    memset(d,0x3f,sizeof(d));
    
    d[1]=0;
    q.push_back(1);vis[1]=true;
    
    while(!q.empty()){
        int u=q.front();q.pop_front();vis[u]=false;
        for(int i=0;i<g[u].size();i++){
            int v=g[u][i].to,value=g[u][i].v;
            if(d[v]>d[u]+value){
                d[v]=d[u]+value;
                if(!vis[v]){
                    if(d[v]<d[!q.empty()&&q.front()])q.push_front(v);
                    else q.push_back(v);
                    vis[v]=true;
                }
            }
        }
    }
}

 

posted @ 2020-10-12 09:42  yesuweiYYYY  阅读(59)  评论(0编辑  收藏  举报