dijkstra堆优化板子

咕咕咕

#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define mk make_pair
#define ll long long
using namespace std;

inline ll read()//快读
{
    ll sum = 0,p = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9')
    {
        if(ch == '-')
            p = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9')
    {
        (sum *= 10) += ch - '0';
        ch = getchar();
    }
    return sum * p;
}

const int N=100005;
const int M=2e5+5;
int n,m,s;
int cnt,head[N];
ll dis[N];
bool vis[N];
struct edge
{
    int nxt,to;
    ll wei;
}e[M];
priority_queue< pair<ll,int> > q;

void add(int x,int y,ll z)
{
    e[++cnt].nxt=head[x];
    e[cnt].to=y;
    e[cnt].wei=z;
    head[x]=cnt;
}

void dijkstra()
{
    memset(dis,0x3f,sizeof(dis));
    dis[s]=0;
    q.push(make_pair(0,s));
    while(q.size())
    {
        int x=q.top().second;
        q.pop();
        if(vis[x])
            continue;
        vis[x]=true;
        for(int i=head[x]; i; i=e[i].nxt)
        {
            int v=e[i].to;
            ll w=e[i].wei;
            if(dis[v]>dis[x]+w)
            {
                dis[v]=dis[x]+w;
                q.push(make_pair(-dis[v],v));
            }
        }
    }
}

int main()
{
    n=read(),m=read(),s=read();
    for(int i=1; i<=m; i++)
    {
        int u=read(),v=read();
        ll w=read();
        add(u,v,w);
    }
    dijkstra();
    for(int i=1; i<=n; i++)
        printf("%lld ",dis[i]);
    return 0;
}

 

posted @ 2019-10-26 14:53  darrrr  阅读(186)  评论(0编辑  收藏  举报