Cod sursa(job #3380163)

Utilizator lefterache_stefanLefterache Stefan lefterache_stefan Data 1 decembrie 2026 21:20:56
Problema Distante Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.24 kb
#include <bits/stdc++.h>
using namespace std;

const int MAXIM = 50005;

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

vector<int> graf[MAXIM];
long long dist[MAXIM];
bool vis[MAXIM];

bool bfsCheck(const int start, const int n) {
	fill(vis + 1, vis + n + 1, false);
	queue<int> q;
	q.push(start);
	vis[start] = true;
	int visitedCount = 1;

	while (!q.empty()) {
		const int u = q.front();
		q.pop();
		for (const int v : graf[u]) {
			if (!vis[v]) {
				vis[v] = true;
				visitedCount++;
				q.push(v);
			}
		}
	}
	return visitedCount == n;
}

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

	while (t--) {
		int n, m, s;
		fin >> n >> m >> s;

		bool ok = true;
		for (int i = 1; i <= n; i++) {
			fin >> dist[i];
			graf[i].clear();
			if (dist[i] < 0) {
				ok = false;
			}
		}
		if (dist[s] != 0) {
			ok = false;
		}

		for (int i = 1; i <= m; i++) {
			int a, b;
			long long c;
			fin >> a >> b >> c;
			if (!ok) {
				continue;
			}
			if (dist[a] + c < dist[b] || dist[b] + c < dist[a]) {
				ok = false;
			} else {
				if (dist[a] + c == dist[b]) {
					graf[a].push_back(b);
				}
				if (dist[b] + c == dist[a]) {
					graf[b].push_back(a);
				}
			}
		}

		if (ok && !bfsCheck(s, n)) {
			ok = false;
		}

		fout << (ok ? "DA\n" : "NU\n");
	}
}