Cod sursa(job #2695918)

Utilizator dianapingu1Diana Vasiliu dianapingu1 Data 14 ianuarie 2021 20:45:17
Problema Algoritmul lui Dijkstra Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int NMAX = 50005;
const int INF = 2e9;

int dist[NMAX];
priority_queue<pair<int,int>> pq;
vector<pair<int,int>> graph[NMAX];

void dijkstra() {

    pair<int,int> a, b;
    a = make_pair(0, 1);
    pq.push(a);
    int node, cost;
    int next_node;
    int next_cost;
    while(!pq.empty()) {
        node = pq.top().second;
        cost = pq.top().first;
        pq.pop();

        if(cost > dist[node])
            continue;

        for(int i = 0; i < graph[node].size(); i++) {
            next_node = graph[node][i].second;
            next_cost = graph[node][i].first;

            if(dist[node] + next_cost < dist[next_node]) {
                dist[next_node] = dist[node] + next_cost;
                next_cost = dist[next_node];
                pq.push(make_pair(next_cost, next_node));
            }
        }
    }
}

int main() {

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

    int n, m;
    fin >> n >> m;
    dist[1] = 0;
    for(int i = 2; i <= n; i++) {
        dist[i] = INF;
    }

    for(int i = 1; i <= m; i++) {
        int x,y,cost;
        fin >> x >> y >> cost;
        graph[x].emplace_back(cost, y);
    }

    dijkstra();

    for(int i = 2; i <= n; i++) {
        if(dist[i] == INF) {
            fout << 0 << " ";
        }
        else {
            fout << dist[i] << " ";
        }
    }

    fin.close();
    fout.close();
    return 0;
}