Cod sursa(job #2036677)

Utilizator anisca22Ana Baltaretu anisca22 Data 10 octombrie 2017 22:24:42
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define INF 0x3f3f3f3f
#define NMAX 50005
#define pii pair <int, int>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

struct str{
    int nod, cost;

    bool operator < (const str &other) const {
        return cost > other.cost;
    }
};

int n, m;
int val[NMAX];
vector <pii> act;
vector <pii> v[NMAX];
priority_queue <str> pq;

void dijkstra()
{
    val[1] = 0;
    pq.push({1, 0});
    while(!pq.empty())
    {
        vector <pii> :: iterator it;
        int nod = pq.top().nod;
        int cost = pq.top().cost;
        pq.pop();
        if (val[nod] != cost) continue;
        for (it = v[nod].begin(); it != v[nod].end(); it++)
        {
            pii nr = *it;
            int nxt = nr.first;
            int cst = nr.second;
            if (val[nod] + cst < val[nxt])
            {
                val[nxt] = val[nod] + cst;
                pq.push({nxt, val[nxt]});
            }
        }
    }
}

int main()
{
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        v[x].push_back(make_pair(y, c));
    }
    for (int i = 1; i <= n; i++)
        val[i] = INF;
    dijkstra();
    for (int i = 2; i <= n; i++)
        if (val[i] != INF)
            fout << val[i] << " ";
        else fout << "0 ";
    return 0;
}