Cod sursa(job #2987091)

Utilizator tudor036Borca Tudor tudor036 Data 1 martie 2023 21:57:22
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <sstream>
#include <iomanip>

#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(NMAX + 2, vector<pair<unsigned int, unsigned int>> (0, make_pair(0, 0)));
stringstream ss;
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 Dijkstra(unsigned int s, vector<unsigned int> &d, vector<unsigned int> &p) {
    int c;
    pair<unsigned int, unsigned int> e;
    vector<bool> u(N + 1);

    d[s] = 0;

    for (unsigned int i = 0; i < N; i++) {
        c = -1;
        for (unsigned int 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 (unsigned int k = 0; k < G[c].size(); k++) {
            unsigned int to = G[c][k].first;
            unsigned int len = G[c][k].second;

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

void Solve() {
    vector<unsigned int> d(N + 2, INF), p(N + 2, -1);
    Dijkstra((unsigned) 1, d, p);

    for (unsigned int i = 2; i <= N; i++) {
        ss << (d[i] > N ? 0 : d[i]) << " ";
    }
}

void Print() {
    Fout << ss.str();
    Fout.close();
}

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