Cod sursa(job #1378902)

Utilizator anarogozAna Rogoz anarogoz Data 6 martie 2015 15:01:42
Problema Algoritmul lui Dijkstra Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include<cstdio>
#include<queue>
#include<vector>
#define INF 1000000000
using namespace std;
const int NMAX = 50000;
struct st
{
    int x, cost;
    st(int x, int cost) {
        this->x = x;
        this->cost = cost;
    };
};

class comp {
    public: inline bool operator() (const st &a, const st &b) {
        return a.cost < b.cost;
    };
};

vector <st> v[NMAX + 1];
st aux = st(0, 0), current = st(0, 0);
priority_queue <st, vector <st>, comp> pq;
int d[NMAX + 2];
int main()
{
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);
    int n, m, a, b, val;
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= m; i++)
    {
        scanf("%d%d%d", &a, &b, &val);
        v[a].push_back(st(b, val));
    }

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

    int nod, c, c2, fiu, l;
    aux.cost = 0;
    aux.x = 1;
    pq.push(aux);
    while(!pq.empty())
    {
        current = pq.top();
        pq.pop();
        c = current.cost;
        nod = current.x;
        l = v[nod].size();
        for(int i = 0; i < l; i++)
        {
            fiu = v[nod][i].x;
            c2 = c + v[nod][i].cost;
            if(c2 < d[fiu])
            {
                d[fiu] = c2;
                pq.push(st(fiu, c2));
            }
        }
    }
    for(int i = 2; i <= n; i++)
    {
        if(d[i] == INF)
            d[i] = 0;
        printf("%d ",d[i]);
    }
    printf("\n");
    return 0;
}