Cod sursa(job #1379070)

Utilizator alexb97Alexandru Buhai alexb97 Data 6 martie 2015 16:07:36
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>
#include <queue>
#define INF 0x3f3f3f3f
using namespace std;

ifstream is("dijkstra.in");
ofstream os("dijkstra.out");

struct Edge{
    int node, cost;
    const bool operator < (const Edge& other) const
    {
        return cost > other.cost;
    }
};

int n, m;
vector<vector<pair<int, int> > >g;
vector<int> d;
vector<bool> s;
priority_queue<Edge> Q;

int main()
{
    is >> n >> m;
    g = vector<vector<pair<int, int> > >(n+1);
    s = vector<bool>(n + 1);
    d = vector<int>(n + 1, INF);
    int x, y, z;
    for(int i = 1; i <= m; ++i)
    {
        is >> x >> y >> z;
        g[x].push_back({y, z});
    }
    Q.push({1, 0});
    d[1] = 0;
    int k;
    while(!Q.empty())
    {
        k = Q.top().node;
        Q.pop();
        for(const auto& y:g[k])
        {
            if(!s[y.first] && d[y.first] > d[k] + y.second)
            {
                d[y.first] = d[k] + y.second;
                s[y.first] = true;
                Q.push({y.first, d[y.first]});

            }
        }
    }
    for(int i = 2; i <= n; ++i)
    {
        os << d[i] << ' ';
    }
    is.close();
    os.close();
    return 0;
}