Cod sursa(job #2864231)

Utilizator NeganAlex Mihalcea Negan Data 7 martie 2022 18:24:30
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 50005;
const int oo = 1e9;
int n, m;
vector<pair<int, int>>V[nmax];
priority_queue<pair<int, int>>pq;
int dist[nmax];
int viz[nmax];

void Dijkstra()
{
    int i, j, x, y, k;
    for(i = 1;i <= n;i++)
        dist[i] = oo;
    dist[1] = 0;
    pq.push({0, 1});
    while(!pq.empty())
    {
        k = pq.top().second;
        pq.pop();
        if(viz[k] == 0)
        {
            viz[k] = 1;
            for(auto x : V[k])
                if(dist[x.first] > dist[k] + x.second)
                {
                    dist[x.first] = dist[k] + x.second;
                    pq.push({-dist[x.first], x.first});
                }
        }
    }
    for(i = 2;i <= n;i++)
        if(dist[i] == oo)
            fout << "0 ";
        else
            fout <<  dist[i] << " ";
}
void Citire()
{
    int x, y, cost, i;
    fin >> n >> m;
    for(i = 1;i <= m;i++)
    {
        fin >> x >> y >> cost;
        V[x].push_back({y, cost});
    }
}

int main()
{
    Citire();
    Dijkstra();
    return 0;
}