Cod sursa(job #877609)

Utilizator tsubyRazvan Idomir tsuby Data 12 februarie 2013 23:40:38
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <cstdio>
#include <vector>
#include <queue>

#define NMAX 50005
#define INFINITY (1<<30)

using namespace std;

int n, m;
int d[NMAX];

struct cmp
{
    bool operator () (const int a, const int b)
    {
        return d[a] > d[b];
    }
};

vector < pair<int, int> > G[NMAX];
priority_queue <int, vector <int>, cmp> Q;

void citire()
{
    int x, y, c;
    scanf("%d %d", &n, &m);
    while(m--)
    {
        scanf("%d %d %d", &x, &y, &c);
        G[x].push_back(make_pair(y,c));
    }
}

void dijkstra(int v)
{
    for(int i=1; i <= n; i++)
    {
        d[i] = INFINITY;
        Q.push(i);
    }
    d[v] = 0;
    while(!Q.empty())
    {
        int x = Q.top();
        Q.pop();
        int l = G[x].size();
        for(int i = 0; i < l; i++)
        {
            int y = G[x][i].first;
            int c = G[x][i].second;
            if(d[y] > d[x] + c)
            {
                d[y] = d[x] + c;
                Q.push(y);
            }
        }
    }
}

void afisare()
{
    for(int i = 2; i <= n; i++)
    {
        if(d[i] != INFINITY)
            printf("%d ", d[i]);
        else
            printf("0 ");
    }
}
int main()
{
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);
    citire();
    dijkstra(1);
    afisare();
    return 0;
}