Cod sursa(job #2899553)

Utilizator preda.andreiPreda Andrei preda.andrei Data 8 mai 2022 22:25:30
Problema Distante Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.69 kb
#include <fstream>
#include <set>
#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;

    multiset<pair<int, int>> heap;
    heap.insert({real[source], source});

    while (!heap.empty()) {
        auto node = heap.begin()->second;
        auto cost = heap.begin()->first;
        heap.erase(heap.begin());

        if (cost > real[node]) {
            continue;
        }
        if (real[node] != dists[node]) {
            return 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;
                heap.insert({real[next], next});
                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;
}