Cod sursa(job #2554062)

Utilizator ViAlexVisan Alexandru ViAlex Data 22 februarie 2020 15:38:21
Problema Sate Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.05 kb
#include<bits/stdc++.h>
using namespace std;

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

struct edge{
	int destination,cost;
};


int num_nodes,num_edges,x,y;
vector<edge> graph[30000];
bool visited[30000];
int dist[30000];


void read(){
	in>>num_nodes>>num_edges>>x>>y;
	int a,b,c;
	for(int i=0;i<num_edges;i++){
		in>>a>>b>>c;
		graph[a-1].push_back({b-1,c});
		graph[b-1].push_back({a-1,c});
	}
}



int bfs(int start,int end){//returns distance between the two parameters
	visited[start]=true;
	dist[start]=0;
	deque<int> que;
	que.push_back(start);

	while(que.size()){
		int here=que.front();
		que.pop_front();
		
		for(int i=0;i<graph[here].size();i++){
			int there=graph[here][i].destination;

			if(!visited[there]){
				visited[there]=true;

				if(there<here)
					dist[there]=dist[here]-graph[here][i].cost;
				else dist[there]=dist[here]+graph[here][i].cost;

				if(there==end){
					return dist[there];
				}

				que.push_back(there);

			}

		}
	}

	return -1;//can't reach destination

}



int main(){
	read();
	out<<bfs(x-1,y-1);
	return 0;
}