Cod sursa(job #2640860)

Utilizator Marius7122FMI Ciltea Marian Marius7122 Data 8 august 2020 17:23:25
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
// Dijkstra's Algorithm
 
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <assert.h>
#include <limits.h>
 
#define ll long long
 
using namespace std;
 
const int N = 200005;
 
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
 
vector<pair<int, int>> g[N];
bool vis[N];
int tata[N], minCost[N];
int n, m;
 
 
int main()
{
    fin >> n >> m;
    for(int i = 0; i < m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        g[x].push_back({y, c});
    }
 
    priority_queue<pair<int, int>> heap;
    heap.push({0, 1});
    for(int i = 2; i <= n; i++)
        minCost[i] = INT_MAX;
 
    int costTotal = 0;
    while(!heap.empty())
    {
        // cout << heap.top().second << ' ' << heap.top().first << '\n';
        int nod = heap.top().second;
        int cost = -heap.top().first;
        heap.pop();
 
        if(vis[nod])
            continue;
 
        vis[nod] = true;
 
        for(auto y : g[nod])
            if(!vis[y.first] && cost + y.second < minCost[y.first])
            {
                heap.push({-(cost + y.second), y.first});
                minCost[y.first] = cost + y.second;
            }
    }

    for(int i = 2; i <= n; i++)
    {
        if(minCost[i] == INT_MAX)
            minCost[i] = 0;
        fout << minCost[i] << ' ';
    }
    return 0;
}