zoukankan      html  css  js  c++  java
  • C++模板:Dijkstra+优先队列

    #include <cstdio>  
    #include <cstring> 
    #include <queue> 
    #include <utility> 
    using namespace std;  
    const int N=20005;  
    const int INF=9999999;  
    typedef pair<int,int>seg;  
    priority_queue<seg,vector<seg>,greater<seg> >q;     
    int d[N],head[N],u[N],v[N],w[N],next[N],n,m,a,b,c; 
    bool vis[N];  
    void build(){  
        memset(head,-1,sizeof(head)); 
        for(int e=1;e<=m;e++){  
            scanf("%d%d%d",&u[e],&v[e],&w[e]);  
            u[e+m]=v[e]; v[e+m]=u[e]; w[e+m]=w[e];  
            next[e]=head[u[e]]; head[u[e]]=e;  
            next[e+m]=head[u[e+m]]; head[u[e+m]]=e+m;  
        }  
    }     
    void Dijkstra(int src){  
        memset(vis,0,sizeof(vis));  
        for(int i=0;i<=n;i++) d[i]=INF;  
        d[src]=0;  
        q.push(make_pair(d[src],src));  
        while(!q.empty()){  
            seg now=q.top(); q.pop();  
            int x=now.second;  
            if(vis[x]) continue; vis[x]=true;  
            for(int e=head[x];e!=-1;e=next[e]) 
            if(d[v[e]]>d[x]+w[e]){  
                d[v[e]]=d[x]+w[e];  
                q.push(make_pair(d[v[e]],v[e]));  
            }   
        }  
    }      
    int main(){  
        while(~scanf("%d%d",&n,&m)&&n+m){build();Dijkstra(1);printf("%d
    ",d[n]);}  
        return 0;  
    }
    
  • 相关阅读:
    python 将字符串转化为可执行代码
    NGS的duplicate的问题
    建库原理
    生信转岗心得
    openpyxl模块处理excel文件
    getopt两个模块getopt 和gun_getopt 的异同
    Migrate repo from Gitlab to Github
    flume(2)
    flume
    docker命令总结
  • 原文地址:https://www.cnblogs.com/forever97/p/3620178.html
Copyright © 2011-2022 走看看