Cod sursa(job #1708657)

Utilizator UPB_Darius_Rares_SilviuPeace my pants UPB_Darius_Rares_Silviu Data 27 mai 2016 18:53:58
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <vector>
#include <cstdio>
#include <queue>
#include <cstring>
#define NMAX 50009
#define oo (1<<30)
#define n first
#define c second
using namespace std;

typedef pair<int, int> edge;

int N, M, d[ NMAX ];
bool inPQ[NMAX];
vector< edge > G[NMAX];


struct cmp {
    bool operator()(const int& x, const int& y) const {
        return d[ x ] > d[ y ];
    }
};
priority_queue <int, vector< int>, cmp> pq;

void Dijkstra(int S) {
    for(int i = 1; i <= N; ++i) {
        d[ i ] = oo;
        inPQ[ i ] = 0;
    }


    pq.push( S );
    d[ S ] = 0;
    inPQ[ S ] = 1;

    while( !pq.empty() ) {
        int node = pq.top();
        pq.pop();
        inPQ[ node ] = 0;

        for (vector< edge >::iterator it = G[node].begin(); it != G[node].end(); ++it) {
            if (d[ node ] + it->c < d[ it-> n]) {
                d[ it->n ] = d[ node ] + it->c;
                if (!inPQ[ it->n ]) {
                    inPQ[ it->n ] = 1;
                    pq.push( it->n );
                }
            }
        }
    }
}

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

    scanf("%d%d", &N, &M);
    while (M--) {
        int x, y, c;
        scanf("%d%d%d", &x, &y, &c);
        G[x].push_back( edge(y, c) );
    }

    Dijkstra(1);

    for (int i = 2; i <= N; ++i) {
        if (d[ i ] == oo) {
            printf("0 ");
        } else {
            printf("%d ", d[ i ]);
        }
    }
    printf("\n");

    return 0;
}