Cod sursa(job #1479912)

Utilizator tudormaximTudor Maxim tudormaxim Data 1 septembrie 2015 17:27:22
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>

using namespace std;
const int nmax = 50005;
const int inf = 1<<29;
vector <pair<int,int> > g[nmax];
int d[nmax], n, m;
class cmp
 {
    public:
        bool operator () (const int &x, const int &y)
        {
            return d[x]>d[y];
        }
 };

void dijkstra()
{
    priority_queue <int, vector<int>, cmp> h;
    int dad, son, cost, i;
    for(i=2; i<=n; i++)
        d[i]=inf;
    h.push(1);
    while(!h.empty())
    {
        dad=h.top();
        h.pop();
        for(i=0; i<g[dad].size(); i++)
        {
            son=g[dad][i].first;
            cost=g[dad][i].second;
            if(d[son] > d[dad]+cost)
            {
                d[son]=d[dad]+cost;
                h.push(son);
            }
        }
    }
}

int main()
{
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);
    int x, y, c, i;
    scanf("%d %d", &n, &m);
    while(m--)
    {
        scanf("%d %d %d", &x, &y, &c);
        g[x].push_back(make_pair(y, c));
    }
    dijkstra();
    for(i=2; i<=n; i++)
    {
        if(d[i]==inf) printf("0 ");
        else printf("%d ", d[i]);
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}