Cod sursa(job #1495278)

Utilizator pulseOvidiu Giorgi pulse Data 2 octombrie 2015 20:42:02
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

const int INF = 2e9;
const int DIM = 50005;
int n, m;
int d[DIM];
bool inq[DIM];
vector < pair <int, int> > g[DIM];
queue <int> q;

void bellman()
{
    for (int i = 2; i <= n; i++)
        d[i] = INF;
    q.push(1);
    while (!q.empty())
    {
        int node = q.front();
        q.pop();
        inq[node] = 0;
        for (vector <pair <int, int> > :: iterator it = g[node].begin(); it != g[node].end(); ++it)
        {
            int v = it -> first;
            int c = it -> second;
            if (d[v] > d[node] + c)
            {
                d[v] = d[node] + c;
                if (!inq[v])
                {
                    q.push(v);
                    inq[v] = 1;
                }
            }
        }
    }
    for (int i = 2; i <= n; i++)
    {
        if (d[i] != INF)
            fout << d[i] << " ";
        else fout << "0 ";
    }
}

int main()
{
    fin >> n >> m;
    for (; m; --m)
    {
        int a, b, c;
        fin >> a >> b >> c;
        g[a].push_back(make_pair(b, c));
    }
    bellman();
    return 0;
}