Cod sursa(job #3155364)

Utilizator andreiomd1Onut Andrei andreiomd1 Data 8 octombrie 2023 03:16:18
Problema Algoritmul lui Dijkstra Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <fstream>
#include <vector>

using namespace std;
using edge = pair<int, int>;

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

static constexpr int NMAX = (int)(5e4 + 1);
static const int INF = (int)(1e9);

int N, M;
vector<edge> G[NMAX];

static inline void read()
{
    f.tie(nullptr);

    f >> N >> M;

    for (int i = 1; i <= M; ++i)
    {
        int a = 0, b = 0;
        f >> a >> b;

        int c = 0;
        f >> c;

        G[a].push_back({c, b});
    }

    return;
}

static inline vector<int> Dijkstra(const int &Source)
{
    vector<int> ans = {};
    vector<bool> Sel = {};
    for (int i = 0; i <= N; ++i)
        ans.push_back(INF), Sel.push_back(0);

    ans[Source] = 0, Sel[Source] = 1;
    for (auto &it : G[Source])
        if (it.first < ans[it.second])
            ans[it.second] = it.first;

    for (int i = 2; i <= N; ++i)
    {
        int Min = (INF + 1), pos = -1;

        for (int j = 1; j <= N; ++j)
            if (!Sel[j] && ans[j] < Min)
                Min = ans[j], pos = j;

        if (pos == -1)
            break;

        Sel[pos] = 1;
        for (auto &it : G[pos])
            if (it.first + ans[pos] < ans[it.second])
                ans[it.second] = it.first + ans[pos];
    }

    for (auto &it : ans)
        if (it == INF)
            it = 0;

    return ans;
}

int main()
{
    read();

    vector<int> dist = Dijkstra(1);

    for (int i = 2; i <= N; ++i)
    {
        g << dist[i];

        if (i < N)
            g << ' ';
        else
            g << '\n';
    }

    return 0;
}