Cod sursa(job #2811438)

Utilizator butasebiButa Gabriel-Sebastian butasebi Data 2 decembrie 2021 11:51:10
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <bits/stdc++.h>
#define INF 1e9
using namespace std;
struct node
{
    int nod;
    int cost;
};
struct pq
{
    bool operator () (node a, node b)
    {
        return a.cost > b.cost;
    }
};
priority_queue<node, vector<node>, pq> Q;
vector <node> v[100005];
int n, m, i, d[100005], dad[100005], x, y, c;
int main()
{
    ifstream f("dijkstra.in");
    ofstream g("dijkstra.out");
    f >> n >> m;
    for(i = 1; i <= n; i ++)
    {
        d[i] = INF;
        dad[i] = 0;
    }
    for(i = 1; i <= m; i ++)
    {
        f >> x >> y >> c;
        node aux;
        aux.nod = y;
        aux.cost = c;
        v[x].push_back(aux);
        if(x == 1)
        {
            d[y] = c;
            dad[y] = x;
            Q.push(aux);
        }
    }
    while(!Q.empty())
    {
        node aux = Q.top();
        Q.pop();
        if(aux.cost != d[aux.nod])continue;
        //cout << aux.nod << " " << aux.cost << "\n";
        for(i = 0; i < v[aux.nod].size(); i ++)
        {
            node aux1 = v[aux.nod][i];
            if(d[aux1.nod] > d[aux.nod] + aux1.cost)
            {
                dad[aux1.nod] = aux.nod;
                d[aux1.nod] = d[aux.nod] + aux1.cost;
                aux1.cost = d[aux1.nod];
                Q.push(aux1);
            }
        }
    }
    for(i = 2; i <= n; i ++)
        if(d[i] != INF)g << d[i] << " ";
        else g << 0 << " ";
    return 0;
}