Cod sursa(job #3126038)

Utilizator AlexMihai1801Mihai Alexandru AlexMihai1801 Data 5 mai 2023 12:27:59
Problema Distante Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.47 kb
#include <bits/stdc++.h>
using namespace std;

// numarul maxim de noduri
#define NMAX 50005

// valoare mai mare decat orice distanta din graf
#define INF (1 << 30)

typedef pair<int, int> iPair;

// structura folosita pentru a stoca distanta, cat si vectorul de parinti
// folosind algoritmul Dijkstra
struct DijkstraResult {
    vector<int> d;
    vector<int> p;

    DijkstraResult(const vector<int>& d, const vector<int>& p)
        : d(d)
        , p(p) { }
};

int n, m, source;
vector<pair<int, int>> adj[NMAX];
vector<int> initial_dist;

DijkstraResult get_result() {
	//
	// TODO: Gasiti distantele minime de la nodul source la celelalte noduri
	// folosind Dijkstra pe graful orientat cu n noduri, m arce stocat in adj.
	//
	// d[node] = costul minim / lungimea minima a unui drum de la source la nodul node
	//     * d[source] = 0;
	//     * d[node] = -1, daca nu se poate ajunge de la source la node.
	//
	// Atentie:
	// O muchie este tinuta ca o pereche (nod adiacent, cost muchie):
	//     adj[node][i] == (neigh, w) - unde neigh este al i-lea vecin al lui node, iar (node, neigh) are cost w.
	//
	vector<int> d(n + 1, INF);
	vector<int> p(n + 1, -1);

	priority_queue<iPair, vector<iPair>, greater<iPair>> pq;

	d[source] = 0;
	pq.push({d[source], source});

	int node;

	while (!pq.empty()) {
		node = pq.top().second;

		pq.pop();

		for (auto &neigh : adj[node]) {
			if (d[node] + neigh.second < d[neigh.first]) {
				d[neigh.first] = d[node] + neigh.second;
				p[neigh.first] = node;

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

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

	return {d, p};
}

bool checkCondition() {
	DijkstraResult result = get_result();
	bool condition = true;
	int initial_size = initial_dist.size();

	for (int i = 1; i < initial_dist.size(); i++) {
		if (initial_dist[i - 1] != result.d[i]) {
			condition = false;
		}
	}

	for (int i = 0 ; i < initial_size; i++) {
		initial_dist.pop_back();
	}
	
	return condition;
}

int main() {
	int tasks;

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

	fin >> tasks;

	int dist, x, y, w;

	for (int i = 0; i < tasks; i++) {
		fin >> n >> m >> source;
		
		for (int j = 0; j < n; j++) {
			adj[j].clear();
			fin >> dist;
			initial_dist.push_back(dist);
		}

		for (int j = 0; j < m; j++) {
			fin >> x >> y >> w;
			adj[x].push_back({y, w});
		}

		if (checkCondition()) {
			fout << "DA\n";
		} else {
			fout << "NU\n";
		}
	}
	
	fin.close();
	fout.close();

    return 0;
}