Cod sursa(job #2581090)

Utilizator PetrescuAlexandru Petrescu Petrescu Data 14 martie 2020 15:34:06
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <bits/stdc++.h>
#define INF 2e9
#define MAX 50001

using namespace std;
typedef pair<int, int>pi;

int dist[MAX];
bool marked[MAX];
priority_queue< pi,vector<pi>,greater<pi> > pq;
vector<pi> graf[MAX];

int main()
{
    int n, m, v, u, cost, i;
    pair<int, int>nod;

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

    ios::sync_with_stdio(false);
    fin.tie(0);
    fout.tie(0);
    srand(time(NULL));

    fin >> n >> m;

    for(i = 0; i < m; i++)
    {
        fin >> v >> u >> cost;

        graf[v].push_back({u, cost});
    }

    for(i = 2; i <= n; i++)
        dist[i] = INF;

    pq.push({0, 1});

    while(!pq.empty())
    {
        nod = pq.top();
        pq.pop();
        marked[nod.second] = true;

        for(auto neighbour : graf[nod.second])
        {
            if(!marked[neighbour.first])
            {
                if(dist[neighbour.first] > dist[nod.second] + neighbour.second)
                {
                    dist[neighbour.first] = dist[nod.second] + neighbour.second;
                    pq.push({dist[neighbour.first], neighbour.first});
                };
            }
        }
    }

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

    fin.close();
    fout.close();

    return 0;
}