Cod sursa(job #2537132)

Utilizator maramihaliMara Mihali maramihali Data 3 februarie 2020 09:49:11
Problema Algoritmul lui Dijkstra Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>

using namespace std;

const int MAX = 50001;
int INF = 0x7f7f7f7f;

vector <pair<int, int>> nod[MAX];
priority_queue <pair<int, int>> heap;
int n, m, dist[MAX];

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

void dijkstra()
{
    memset(dist, INF, sizeof dist);
    heap.push(make_pair(0, 1));
    dist[1] = 0;
    while(!heap.empty())
    {
        int acost = -heap.top().first;
        int from = heap.top().second;
        heap.pop();
        if(acost == from)
        {
            break;
        }
        for(pair <int, int> way : nod[from])
        {
            int to = way.first;
            int newcost = acost + way.second;
            if(newcost < dist[to])
            {
                heap.push(make_pair(-newcost, to));
                dist[to] = newcost;
            }
        }
    }
}

int main()
{
    in >> n >> m;
    while(m)
    {
        m--;
        int x, y, cost;
        in >> x >> y >> cost;
        nod[x].push_back(make_pair(y, cost));
    }
    dijkstra();
    for (int i = 2; i <= n; i++)
        if (dist[i] == INF)
            out << 0 << ' ';
        else
            out << dist[i] << ' ';
    return 0;
}