Cod sursa(job #2121772)

Utilizator hantoniusStan Antoniu hantonius Data 4 februarie 2018 12:29:56
Problema Algoritmul lui Dijkstra Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
#define MAXN 50001
using namespace std;

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

vector <pair <int, int> > v[MAXN];
priority_queue <pair <int, int> > min_heap;
int viz[MAXN], dist[MAXN], n, m;

void read()
{
    int x, y, c;

    fin >> n >> m;
    for (int i = 0; i < m; ++i) {
        fin >> x >> y >> c;
        v[x].push_back(make_pair(y, c));
    }
}

void write()
{
    for (int i = 2; i <= n; ++i)
        if (dist[i] != INT_MAX)
            fout << dist[i] << ' ';
        else
            fout << "0 ";
}

/*
void solve()
{
    int minv, poz;
    vector <pair <int, int> >::iterator it;

    for (int i = 1; i <= n; ++i)
        dist[i] = INT_MAX;
    viz[1] = 1;
    for (it = v[1].begin(); it != v[1].end(); ++it)
        dist[it->first] = it->second;
    while (true) {
        minv = INT_MAX;
        for (int i = 2; i <= n; ++i)
            if (viz[i] == 0 && dist[i] < minv) {
                poz = i;
                minv = dist[i];
            }
        if (minv == INT_MAX)
            return;
        viz[poz] = 1;
        for (it = v[poz].begin(); it != v[poz].end(); ++it)
            if (dist[it->first] > dist[poz] + it->second)
                dist[it->first] = dist[poz] + it->second;
    }
}
*/

void solve()
{
    vector <pair <int, int> >::iterator it;
    int aux;

    for (int i = 2; i <= n; ++i)
        dist[i] = INT_MAX;
    dist[1] = 0;
    viz[1] = 1;
    min_heap.push(make_pair(0, 1));
    while (min_heap.empty() == false) {
        aux = min_heap.top().second;
        min_heap.pop();
        for (it = v[aux].begin(); it != v[aux].end(); ++it)
            if (dist[it->first] > dist[aux] + it->second) {
                dist[it->first] = dist[aux] + it->second;
                if (viz[it->first] == 0) {
                    viz[it->first] = 1;
                    min_heap.push(make_pair(-dist[it->first], it->first));
                }
            }
    }
}

int main()
{
    read();
    solve();
    write();
    return 0;
}