Cod sursa(job #561540)

Utilizator UpL1nKPaunescu Sorin UpL1nK Data 20 martie 2011 18:33:44
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <cstdio>
#include <queue>
#define INF 1000000001

using namespace std;

struct nod {

    int inf;
    int cost;
    nod *next;

} *G[50001];

int n, m;
int cost[50001], used[50001];

queue<int> Q;

void insert(int, int, int);
void BF();

int main() {

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

    scanf("%d %d", &n, &m);

    int x, y, c;

    for (int i = 1; i <= m; i++) {

        scanf("%d %d %d", &x, &y, &c);
        insert(x, y, c);

    }

    BF();

    for (int i = 2; i <= n; i++)
        if (cost[i] == INF)
            printf("0 ");
        else
            printf("%d ", cost[i]);

    return 0;
}

void insert(int x, int y, int c) {

    nod *nou = new nod;
    nou->inf = y;
    nou->cost = c;
    nou->next = G[x];
    G[x] = nou;

}

void BF() {

    for (int i = 2; i <= n; i++)
        cost[i] = INF;

    Q.push(1);
    used[1] = 1;

    int x;

    while (!Q.empty()) {

        x = Q.front();
        Q.pop();
        used[x] = 0;

        for (nod *p = G[x]; p; p = p->next) {
            if (cost[p->inf] > cost[x] + p->cost) {
                cost[p->inf] = cost[x] + p->cost;
                if (!used[p->inf]) {
                    Q.push(p->inf);
                    used[p->inf] = 1;
                }
            }
        }

    }

}