Cod sursa(job #3296623)

Utilizator Sergiu24Ivan Sergiu Sergiu24 Data 14 mai 2025 17:33:24
Problema Distante Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.79 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <utility>
#include <algorithm>
#include <queue>
#include <limits.h>
using namespace std;

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

int main() {
    int T;
    fin >> T;

    for(int i = 0; i < T; i++) {
        int N, M, S;
        fin >> N >> M >> S;
        S--; // Adjust for 0-based indexing

        vector<int> dist(N);
        for(int j = 0; j < N; j++) {
            fin >> dist[j];
        }

        vector<pair<int, int>> adj[N];
        for(int j = 0; j < M; j++) {
            int x, y, w;
            fin >> x >> y >> w;
            x--; y--; // Adjust for 0-based indexing
            adj[x].push_back({y, w});
            adj[y].push_back({x, w}); // Undirected graph
        }

        // Dijkstra
        vector<int> d(N, INT_MAX);
        d[S] = 0;

        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
        pq.push({0, S});

        while(!pq.empty()) {
            int node = pq.top().second;
            int dist_to_node = pq.top().first;
            pq.pop();

            if(dist_to_node > d[node]) continue;

            for(auto edge : adj[node]) {
                int neigh = edge.first;
                int weight = edge.second;

                if(d[neigh] > d[node] + weight) {
                    d[neigh] = d[node] + weight;
                    pq.push({d[neigh], neigh});
                }
            }
        }

        bool is_correct = true;
        for(int j = 0; j < N; j++) {
            if(d[j] != dist[j]) {
                is_correct = false;
                break;
            }
        }

        if(is_correct) {
            fout << "DA\n";
        } else {
            fout << "NU\n";
        }
    }

    fin.close();
    fout.close();
    return 0;
}