Cod sursa(job #2987096)

Utilizator tudor036Borca Tudor tudor036 Data 1 martie 2023 22:05:40
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <iostream>
#include <fstream>
#include <vector>

#define NMAX 50000

using namespace std;

ifstream Fin("dijkstra.in");
ofstream Fout("dijkstra.out");

constexpr int INF = 0x3F3F3F3F;

vector<vector<pair<unsigned int, unsigned int>>> G;
vector<unsigned int> d, p;
unsigned int N, M;

void Read() {
    unsigned int x, y, w;
    Fin >> N >> M;

    G.resize(N + 1);

    while (M--) {
        Fin >> x >> y >> w;
        G[x].push_back(make_pair(y, w));
    }

    Fin.close();
}

void Solve() {
    pair<unsigned int, unsigned int> e;
    vector<bool> u(N + 1);
    unsigned int i, j, k, to, len;
    int c;

    d.assign(static_cast<vector<unsigned int, std::allocator<unsigned int>>::size_type>(N) + 1, INF);
    p.assign(static_cast<vector<unsigned int, std::allocator<unsigned int>>::size_type>(N) + 1, -1);

    d[1] = 0;

    for (i = 0; i < N; i++) {
        c = -1;
        for (j = 1; j <= N; j++) {
            if (!u[j] && (c == -1 || d[j] < d[c])) {
                c = (signed) j;
            }
        }

        if (d[c] == INF) {
            break;
        }

        u[c] = true;
        for (k = 0; k < G[c].size(); k++) {
            to = G[c][k].first;
            len = G[c][k].second;

            if (d[c] + len < d[to]) {
                d[to] = d[c] + len;
                p[to] = (unsigned) c;
            }
        }
    }
}

void Print() {
    for (unsigned int i = 2; i <= N; i++) {
        Fout << (d[i] > N ? 0 : d[i]) << " ";
    }
    Fout.close();
}

int main()
{
    Read();
    Solve();
    Print();
    
    return 0;
}