Pagini recente » Cod sursa (job #1677960) | Cod sursa (job #2945249) | Cod sursa (job #307769) | Cod sursa (job #1185227) | Cod sursa (job #3323364)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
std::ifstream in("sate.in");
std::ofstream out("sate.out");
struct neighbour_t {
long long dist = 0;
unsigned idx;
neighbour_t(unsigned idx, long long dist):
dist(dist),
idx(idx)
{}
};
struct node_t {
std::vector<neighbour_t> neighbours;
};
long long sate_dist(node_t* const graph, bool* const checked, unsigned const at, unsigned const target, long long const dist) {
checked[at] = true;
for(neighbour_t neighbour : graph[at].neighbours) {
if(checked[neighbour.idx]) continue;
if(neighbour.idx == target) {
return dist + neighbour.dist;
}
long long new_dist = sate_dist(graph, checked, neighbour.idx, target, dist + neighbour.dist);
if(new_dist != -1) return new_dist;
}
return -1;
}
int main() {
unsigned nodes, edges, start, end;
in >> nodes >> edges >> start >> end;
if(start == end) {
out << "0";
return 0;
}
if(start > end) {
unsigned _ = start;
start = end;
end = _;
}
node_t graph[30001];
bool checked[30001];
std::memset(checked, 0, 30001);
unsigned a, b;
long long d;
for(unsigned edge = 0; edge < edges; edge += 1) {
in >> a >> b >> d;
graph[a].neighbours.push_back( neighbour_t(b, d) );
graph[b].neighbours.push_back( neighbour_t(a, -d) );
}
out << sate_dist(graph, checked, start, end, 0);
}