模板——Dijkstra算法+堆优化

#include<bits/stdc++.h>
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=600010;
struct point{
    int start,cost;
};
bool operator < (const point &m,const point &n){
    return m.cost>n.cost;
}
struct edge{
    int to,cost;
};
vector <edge> e[maxn];
bool judge[maxn];
int len[maxn];
int sta;
point add(int x,int y){
    point rem;
    rem.start=x;
    rem.cost=y;
    return rem;
}
void addedge(int u,int v,int w){
    edge rem;
    rem.to=v;
    rem.cost=w;
    e[u].push_back(rem);
}
void dijkstra(int n,int start){
    memset(judge,false,sizeof(judge));
    for (int i=1; i<=n; i++) len[i]=INF;
    priority_queue <point> que;
    while (!que.empty()) que.pop();
    len[start]=0;
    que.push(add(start,0));
    point tem;
    while (!que.empty()){
        tem=que.top();
        que.pop();
        int u=tem.start;
        if (judge[u]) continue;
        judge[u]=true;
        for (int i=0; i<e[u].size(); i++){
            int v=e[tem.start][i].to;
            int cost=e[u][i].cost;
            if (!judge[v] && len[v]>len[u]+cost){
                len[v]=len[u]+cost;
                que.push(add(v,len[v]));
            }
        }
    }
}
int main(){
    for (int i=0; i<=maxn; i++)
        if (!e[i].empty())
            e[i].clear();
            int n,e;
            cin>>n>>e>>sta;
            for (int i=1; i<=e; i++){
                int u,v,w;
                cin>>u>>v>>w;
                addedge(u,v,w);
            }
            dijkstra(n,sta);
            for (int i=1; i<=n; i++)
                cout<<len[i]<<" ";
                cout<<endl;
                return 0;
}

  

posted @ 2017-09-11 16:44  |斗蜂|  阅读(407)  评论(0编辑  收藏  举报