Cod sursa(job #3257950)

Utilizator Dragu_AndiDragu Andrei Dragu_Andi Data 20 noiembrie 2024 11:10:38
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

struct nod{
    int val;
    int cost;

    bool operator < (const nod &other) const{
        return cost > other.cost;
    }
};

const int nmax=5e4 +1, inf = 1e9 + 1;
vector<nod> G[nmax];
int dist[nmax], n;
priority_queue<nod> heap;

void dijkstra(int start){
    for(int i=0; i<=n; i++)
        dist[i]=inf;
    dist[start]=0;
    heap.push({start, 0});
    while(!heap.empty())
    {
        nod cur = heap.top();
        heap.pop();
        if(dist[cur.val]  < cur.cost)
            continue;
        for(nod vecin: G[cur.val])
        {
            if(dist[cur.val] + vecin.cost < dist[vecin.val])
            {
                dist[vecin.val] = vecin.cost + dist[cur.val];
                heap.push({vecin.val, dist[vecin.val]});
            }
        }
    }
}

int main()
{
    int m;
    fin >> n >> m;
    int x, y, z;
    for(int i=0; i<n; i++)
    {
        fin >> x >> y >> z;
        G[x].push_back({y, z});
    }
    dijkstra(1);
    for(int i=2; i<=n; i++)
    {
        if(dist[i]!=inf)
            fout << dist[i] << ' ';
        else
            fout << 0;
    }
    return 0;
}