Cod sursa(job #2673497)

Utilizator cristi_macoveiMacovei Cristian cristi_macovei Data 17 noiembrie 2020 00:53:14
Problema Distante Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.88 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <algorithm>

class Edge {
public:
  int node;
  int cost;

  Edge() = default;

  Edge(int node, int cost):
    node(node), cost(cost) {};
};

class QElem {
public:
  int node;
  int dist;

  QElem() = default;

  QElem(int node, int dist):
    node(node), dist(dist) {};

  bool operator < (const QElem& other) const {
    return this->dist < other.dist;
  }

  bool operator > (const QElem& other) const {
    return this->dist > other.dist;
  }
};

int tests, n, m, start;

std::vector<std::vector<Edge>> graph;

std::priority_queue<QElem, std::vector<QElem>, std::greater<>> pq;

std::vector<int> dist, a;

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

  while (!pq.empty()) {
    int node = pq.top().node;
    int distance = pq.top().dist;
    pq.pop();

    if (distance > dist[node])
      continue;

    for (Edge& edge: graph[node]) {
      if (dist[edge.node] == -1 || dist[edge.node] > distance + edge.cost) {
        dist[edge.node] = distance + edge.cost;
        pq.emplace(edge.node, dist[edge.node]);
      }
    }
  }
}

int main() {
  std::ifstream in("distante.in");
  std::ofstream out("distante.out");

  in >> tests;

  for (int t = 1; t <= tests; ++t) {

    in >> n >> m >> start;

    graph = std::vector<std::vector<Edge>>(n + 1);

    dist = std::vector<int>(n + 1);
    a = std::vector<int>(n + 1);

    std::fill(dist.begin(), dist.end(), -1);

    for (int i = 1; i <= n; ++i)
      in >> a[i];

    int x, y, cost;
    for (int i = 1; i <= m; ++i) {
      in >> x >> y >> cost;

      graph[x].emplace_back(y, cost);
      graph[y].emplace_back(x, cost);
    }

    dijkstra();

    bool broken = false;
    for (int i = 1; i <= n; ++i) {
      if (dist[i] != a[i]) {
        out << "NU\n";
        broken = true;
        break;
      }
    }
    if (!broken)
      out << "DA\n";
  }

  return 0;
}