Cod sursa(job #3378281)

Utilizator FilipbosBogdan Filip Filipbos Data 25 noiembrie 2026 18:00:05
Problema Distante Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.05 kb
#include <fstream>
#include <vector>
#include <queue>


class comp {
public:
    bool operator()(std::pair<int, int> a, std::pair<int, int> b) const {
        return a.second > b.second;
    }
};

std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, comp> pq;
std::vector<std::vector<std::pair<int, int>>> adj; // adj[i] = {j,cost}
std::vector<int> d; // d[i] = costul drumului minim pana la i
std::vector<long long> solutii; // solutile prietenului
const int INF = 1e9;

std::ifstream f("distante.in");
std::ofstream g("distante.out");

void dijkstra(int start) {
    pq.emplace(start,0);
    d[start] = 0;

    while (!pq.empty()) {
        int i = pq.top().first;
        int cost_curent = pq.top().second;
        pq.pop();
        // extragem primul element

        if (d[i] < cost_curent)
            continue;
        //daca nu e un improvement

        for (auto vec : adj[i]) {
            int j = vec.first;
            int cost_vecin = vec.second;

            if (d[j] > d[i] + cost_vecin) {
                d[j] = d[i] + cost_vecin;
                pq.emplace(j,d[j]);
            }
        }
    }
}

int main() {
    int h;
    f >> h;
    for (int h1 = 0; h1 < h; h1++) {
        int n,m,start;
        int ok = 1; // flag care ramane 1 daca solutia e buna
        f >> n >> m >> start;

        solutii.clear();
        d.clear();
        adj.clear();

        solutii.resize(n + 1);
        d.resize(n + 1,INF);
        adj.resize(n + 1);

        for (int i = 1; i <= n; i++)
            f >> solutii[i];
        
        for (int i = 0; i < m; i++) {
            int x,y,c;
            f >> x >> y >> c;

            adj[x].emplace_back(y,c);
            adj[y].emplace_back(x,c);
        }

        dijkstra(start);
        for (int i = 1; i <= n; i++) {
            if (d[i] != solutii[i]) {
                g << "NU" << '\n';
                ok = 0;
                break;
            }
        }

        if (ok)
            g << "DA" << '\n';
    }

    return 0;
}