Cod sursa(job #1360301)

Utilizator mirceadinoMircea Popoveniuc mirceadino Data 25 februarie 2015 13:39:34
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include<cstdio>
#include<vector>
#include<queue>
#include<string>

using namespace std;

#ifdef HOME
const string inputFile = "input.txt";
const string outputFile = "output.txt";
#else
const string problemName = "dijkstra";
const string inputFile = problemName + ".in";
const string outputFile = problemName + ".out";
#endif

typedef pair<int, int> PII;
const int INF = (1 << 30);
const int NMAX = 50000 + 5;

int N, M;
int D[NMAX];
vector<PII> V[NMAX];
priority_queue<PII, vector<PII>, greater<PII> > PQ;

void dijkstra(int x) {
    int i, y, z;

    for(i = 1; i <= N; i++)
        D[i] = INF;

    D[x] = 0;
    PQ.push(make_pair(D[x], x));

    while(!PQ.empty()) {
        x = PQ.top().second;
        PQ.pop();

        for(auto it : V[x]) {
            y = it.first;
            z = it.second;
            if(D[x] + z < D[y]) {
                D[y] = D[x] + z;
                PQ.push(make_pair(D[y], y));
            }
        }
    }
}

int main() {
    int i, x, y, z;

    freopen(inputFile.c_str(), "r", stdin);
    freopen(outputFile.c_str(), "w", stdout);

    scanf("%d%d", &N, &M);

    while(M--) {
        scanf("%d%d%d", &x, &y, &z);
        V[x].push_back(make_pair(y, z));
    }

    dijkstra(1);

    for(i = 2; i <= N; i++)
        printf("%d ", D[i] == INF ? 0 : D[i]);

    return 0;
}