Cod sursa(job #2899576)

Utilizator preda.andreiPreda Andrei preda.andrei Data 8 mai 2022 22:30:04
Problema Distante Scor 60
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.61 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

using Graph = vector<vector<pair<int, int>>>;

bool Solve(Graph& graph, int source, const vector<int>& dists) {
    vector<int> real(graph.size(), 1 << 30);
    real[source] = 0;

    queue<int> q;
    q.push(source);

    vector<bool> in_q(graph.size(), false);
    in_q[source] = true;

    while (!q.empty()) {
        auto node = q.front();
        q.pop();
        in_q[node] = false;

        for (const auto& edge : graph[node]) {
            auto next = edge.first;
            auto cost = edge.second;
            if (real[node] + cost < real[next]) {
                real[next] = real[node] + cost;
                if (!in_q[next]) {
                    q.push(next);
                    in_q[next] = true;
                }
                if (real[next] < dists[next]) {
                    return false;
                }
            }
        }
    }
    return real == dists;
}

int main() {
    ifstream fin("distante.in");
    ofstream fout("distante.out");

    int tests;
    fin >> tests;

    for (int i = 0; i < tests; i += 1) {
        int nodes, edges, source;
        fin >> nodes >> edges >> source;

        vector<int> dists(nodes);
        for (auto& dist : dists) {
            fin >> dist;
        }

        Graph graph(nodes);
        for (int j = 0; j < edges; j += 1) {
            int a, b, cost;
            fin >> a >> b >> cost;
            graph[a - 1].push_back({b - 1, cost});
            graph[b - 1].push_back({a - 1, cost});
        }
        fout << (Solve(graph, source - 1, dists) ? "DA" : "NU") << "\n";
    }
    return 0;
}