Cod sursa(job #3130275)

Utilizator ioana3317ioanapopescu ioana3317 Data 17 mai 2023 14:35:49
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int N = 5e4;
const int INF = 1 << 30;

struct succesor
{
    int vf, c;
};

int n, d[N+1];
bool selectat[N+1];
vector <succesor> ls[N+1];
priority_queue <pair<int, int>> h;

void dijkstra(int x0)
{
    for (int i = 1; i <= n; i++)
    {
        d[i] = INF;
    }
    d[x0] = 0;
    h.push({0, x0});
    while (!h.empty())///h este nevid
    {
        int x = h.top().second;
        h.pop();
        if (selectat[x])
        {
            continue;
        }
        selectat[x] = true;
        for (auto s: ls[x])
        {
            int y = s.vf;
            int c = s.c;
            if (selectat[y])
            {
                continue;
            }
            if (d[x] + c < d[y])
            {
                d[y] = d[x] + c;
                h.push({-d[y], y});
            }
        }
    }
}

int main()
{
    ifstream in("dijkstra.in");
    ofstream out("dijkstra.out");
    int m;
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;
        ls[x].push_back((succesor){y, c});
    }
    dijkstra(1);
    for (int i = 2; i <= n; i++)
    {
        if (d[i] == INF)
        {
            d[i] = 0;
        }
        out << d[i] << " ";
    }
    in.close();
    out.close();
    return 0;
}