Cod sursa(job #1481140)

Utilizator dnprxDan Pracsiu dnprx Data 3 septembrie 2015 21:47:55
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <bits/stdc++.h>

using namespace std;

struct Nod
{
    int nod, cost;
    bool operator < (const Nod& e) const
	{
        return cost > e.cost;
    }
};

vector <Nod> h[50001];
int n, d[50001];

void Citire()
{
    int x, y, c, i, m;
    Nod w;
    ifstream fin("dijkstra.in");
    fin >> n >> m;
    for (i = 1; i <= m; ++i)
    {
        fin >> x >> y >> c;
        w.nod = y;
        w.cost = c;
        h[x].push_back(w);
    }
    fin.close();
}

void Dijkstra()
{
    priority_queue<Nod> q;
    Nod w, w1;
    int i, k, j, c;
    for (i = 2; i <= n; i++)
        d[i] = 1000000000;
    d[1] = 0;
    w.nod = 1;
    w.cost = 0;
    q.push(w);
    while (!q.empty())
    {
        w = q.top();
        q.pop();
        k = w.nod;
        for (i = 0; i < h[k].size(); i++)
        {
            j = h[k][i].nod;
            c = h[k][i].cost;
            if (d[j] > d[k] + c)
            {
                d[j] = d[k] + c;
                w1.nod = j;
                w1.cost = d[j];
                q.push(w1);
            }
        }
    }
}

void Afisare()
{
    int i;
    ofstream fout("dijkstra.out");
    for (i = 2; i <= n; i++)
        if (d[i] < 1000000000) fout << d[i] << " ";
        else fout << "0 ";
    fout << "\n";
    fout.close();
}

int main()
{
    Citire();
    Dijkstra();
    Afisare();
    return 0;
}