Cod sursa(job #3265576)

Utilizator stefan0211Tacu Darius Stefan stefan0211 Data 31 decembrie 2024 16:33:38
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;

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

struct ComparePairs
{
    bool operator()(const pair<int, int> &p1, const pair<int, int> &p2)
    {
        return p1.second > p2.second;
    }
};

int main()
{
    int n, m;
    f >> n >> m;

    vector<vector<pair<int, int>>> adj(n + 1); // Lista de adiacență
    vector<int> d(n + 1, INT_MAX);
    d[1] = 0;
    vector<int> tata(n + 1, 0);

    int x, y, c;
    for (int i = 1; i <= m; i++)
    {
        f >> x >> y >> c;
        adj[x].push_back(make_pair(y, c));
    }

    priority_queue<pair<int, int>, vector<pair<int, int>>, ComparePairs> pq;
    pq.push({1, 0});
    // for (int i = 1; i <= n; i++)
    // {
    //     pq.push({i, d[i]});
    // }

    vector<bool> viz(n + 1, false);

    while (!pq.empty())
    {
        auto nod_curent = pq.top().first;
        pq.pop();

        if (viz[nod_curent])
            continue;

        viz[nod_curent] = true;
        for (auto &v : adj[nod_curent])
        {
            if (viz[v.first])
                continue;

            if (d[nod_curent] + v.second < d[v.first])
            {
                d[v.first] = d[nod_curent] + v.second;
                v.second = d[v.first];
                tata[v.first] = nod_curent;
                pq.push({v.first, d[v.first]});
            }
        }
    }
    for (int i = 2; i <= n; i++)
    {
        if (d[i] == INT_MAX)
        {
            g << "0 "; // Dacă nu există drum
        }
        else
        {
            g << d[i] << " "; // Lungimea drumului minim
        }
    }

    return 0;
}