Cod sursa(job #3373858)

Utilizator lefterache_stefanLefterache Stefan lefterache_stefan Data 7 noiembrie 2026 23:10:35
Problema Sate Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.09 kb
#include <bits/stdc++.h>

#include <optional>
using namespace std;

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

const int MAXIM = 30005;
vector<pair<int, int>> graf[MAXIM];
vector<pair<int, int>> grafInvers[MAXIM];
map<pair<int, int>, int> muchii;

optional<int> dist(const int a, const int b) {
	if (muchii.count({a, b})) {
		return muchii[{a, b}];
	}
	// a -> c -> b
	for (const auto& muchie : graf[a]) {
		const int c = muchie.first;
		const int costAC = muchie.second;
		const auto other = dist(c, b);
		if (other.has_value()) {
			const int costCB = other.value();
			return costAC + costCB;
		}
	}
	for (const auto& muchie : grafInvers[b]) {
		const int c = muchie.first;
		const int costCB = muchie.second;
		const auto other = dist(a, c);
		if (other.has_value()) {
			const int costAC = other.value();
			return costAC + costCB;
		}
	}
	return nullopt;
}

int main() {
	int n, m, x, y;
	fin >> n >> m >> x >> y;
	for (int i = 0; i < m; i++) {
		int a, b, c;
		fin >> a >> b >> c;
		graf[a].push_back({b, c});
		grafInvers[b].push_back({a, c});
		muchii[{a, b}] = c;
	}
	fout << dist(x, y).value();
}