Cod sursa(job #1511688)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 27 octombrie 2015 00:58:00
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <bits/stdc++.h>
#define Nmax 50005
#define INF 0x3f3f3f3f
using namespace std;
int DP[Nmax];
vector<pair<int,int> > G[Nmax];
priority_queue<pair<int,int> > Q;
int N,M;

void Read()
{
    scanf("%d%d",&N,&M);
    int A,B,C;
    for(int i = 1; i <= M; ++i)
    {
        scanf("%d%d%d",&A,&B,&C);
        G[A].push_back({C,B});
        G[B].push_back({C,A});
    }
}

void Dijkstra(int k)
{
    memset(DP,INF,sizeof(DP));
    DP[k] = 0;
    Q.push({0,k});
    int nodc,cost;
    while(!Q.empty())
    {
        cost = -Q.top().first;
        nodc = Q.top().second;
        Q.pop();
        if(cost != DP[nodc])
            continue;

        for(auto it : G[nodc])
            if(DP[it.second] > DP[nodc] + it.first)
            {
                DP[it.second] = DP[nodc] + it.first;
                Q.push({-DP[it.second],it.second});
            }
    }
    for(int i = 2; i <= N; ++i)
        if(DP[i] == INF) printf("0 ");
        else printf("%d ",DP[i]);
}

int main()
{
    freopen("dijkstra.in","r",stdin);
    freopen("dijkstra.out","w",stdout);

    Read();
    Dijkstra(1);

    return 0;
}