Cod sursa(job #2236204)

Utilizator anisca22Ana Baltaretu anisca22 Data 28 august 2018 17:04:28
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>
#define pii pair <int, int>
#define NMAX 50005
#define INF 0x3f3f3f3f

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 drum[NMAX];
priority_queue <str> pq;
vector <pii> v[NMAX];

void dijkstra()
{
    pq.push({1, 0});
    drum[1] = 0;

    while (!pq.empty())
    {
        int nod = pq.top().nod;
        int cost = pq.top().cost;
        pq.pop();
        if (cost != drum[nod])continue;

        for (auto it = v[nod].begin(); it != v[nod].end(); it++)
        {
            int nxt = (*it).first;
            int cst = (*it).second;

            if (drum[nod] + cst < drum[nxt])
            {
                drum[nxt] = drum[nod] + cst;
                pq.push({nxt, drum[nxt]});
            }
        }
    }
}

int main()
{
    memset(drum, INF, sizeof(drum));
    fin >> N >> M;
    for (int i = 1; i <= M; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        v[x].push_back({y, c});
    }
    dijkstra();
    for (int i = 2; i <= N; i++)
        fout << drum[i] << " ";

    return 0;
}