Cod sursa(job #3226524)

Utilizator madalina.andronacheAndronache Madalina madalina.andronache Data 21 aprilie 2024 17:56:38
Problema Distante Scor 0
Compilator cpp-32 Status done
Runda Arhiva de probleme Marime 2.02 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>

using namespace std;

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

#define NMAX 50001
#define INF 1e9

int n;
int dist[NMAX]; // distantele primite ca input
vector<pair<int, int>> adj[NMAX]; // ptr fiecare nod salvez perechea (neigh, weight)
int d[NMAX];
int p[NMAX]; // vectori de distante, parinti

void dijkstra(int source){
    for(int i = 1; i <= n; i++) {
        p[i] = -1;
        d[i] = INF;
    }

    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; // (disatanta, nodul)
    d[source] = 0;
    p[source] = 0;

    pq.push({0, source});
    while(!pq.empty()) {
        int distance = pq.top().first;
        int node = pq.top().second;

        pq.pop();
        if(distance > d[node]) {
            continue;
        }

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

            if(d[node] + weight < d[neigh]) {
                d[neigh] = d[node] + weight;
                p[neigh] = node;

                pq.push({d[neigh],neigh});
            }
        }
    }

    for (int i = 1; i <= n; ++i) {
        if (d[i] == INF) {
            d[i] = -1;
        }
    }
}


int main() {
    int t, m, a, b, c, source;

    fin >> t; // nr. de grafuri
    for(int i = 1; i <= t; i++) {
        fin >> n >> m >> source;

        for(int j = 1; j <= n; j++) {
            fin >> dist[j]; // distantele calculate
        }

        for(int j = 1; j <= m; j++) {
            fin >> a >> b >> c;
            adj[a].push_back({b, c});
        }

        dijkstra(source);

        bool ok = true;
        for(int j = 1; j <= n; j++) {
            if(dist[j] != d[j]) {
                ok = false;
                break;
            }
        }

        if(ok == true) {
            fout << "DA\n";
        } else {
            fout << "NU\n";
        }
    }


    return 0;
}