Cod sursa(job #3145496)

Utilizator daristyleBejan Darius-Ramon daristyle Data 15 august 2023 22:34:44
Problema Sate Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.96 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

struct Edge{
		short node;
		int cost;
};

const int N_MAX = 3e4;
vector<Edge> edge[N_MAX];
int cost[N_MAX]{};

inline int sgn(int x){
	return (x) ? ((x < 0) ? -1 : 1) : 0;
}

int bfs(short start, short stop){
	queue<short> q;

	q.push(start);
	cost[start] = 1;

	while(!cost[stop]){
		int node = q.front();
		q.pop();

		for(auto neighbour: edge[node])
			if(!cost[neighbour.node]){
				cost[neighbour.node] = cost[node] + neighbour.cost * sgn(neighbour.node - node);
				q.push(neighbour.node);
			}
	}

	return cost[stop] - 1;
}

int main(){
	int nodes, edges, start, stop, a, b, w;
	fin >> nodes >> edges >> start >> stop;
	--start;
	--stop;
	for(int i = 0; i < edges; ++i){
		fin >> a >> b >> w;
		--a;
		--b;

		edge[a].push_back({b, w});
		edge[b].push_back({a, w});
	}

	fout << bfs(start, stop) << '\n';

	fin.close();
	fout.close();
	return 0;
}