Cod sursa(job #1442643)

Utilizator tweetyMarinescu Ion tweety Data 25 mai 2015 22:54:21
Problema Sate Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.49 kb
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;

ifstream In("sate.in");
ofstream Out("sate.out");
vector<pair<int, int> >* Neighbours;
queue<int> Queue;
int* Dist;
int NodesNo;
int EdgesNo;
int X;
int Y;

void alloc()
{
	Neighbours = new vector<pair<int, int> >[NodesNo];
	Dist = new int[NodesNo];

	memset(Dist, 0, sizeof(int) * NodesNo);
}

void init()
{
	--X;
	--Y;
}

void dealloc()
{
	delete[] Neighbours;
	delete[] Dist;
}

void readData()
{
	In >> NodesNo >> EdgesNo >> X >> Y;
	init();
	alloc();

	for (int i = 0, x, y, c; i != EdgesNo; ++i)
	{
		In >> x >> y >> c;
		Neighbours[x - 1].push_back(make_pair(y - 1, c));
		Neighbours[y - 1].push_back(make_pair(x - 1, c));
	}

	In.close();
}

void printData()
{
	Out << Dist[Y] << " ";
	Out.close();
}


void addToQueue(const int& node)
{
	Queue.push(node);
}

int removeFromQueue()
{
	int node = Queue.front();
	Queue.pop();

	return node;
}

void solve()
{
	addToQueue(X);

	while (!Queue.empty())
	{
		int node = removeFromQueue();

		for (auto it = Neighbours[node].begin(); it != Neighbours[node].end(); ++it)
			if (Dist[it->first] == 0)
			{
				addToQueue(it->first);
				int toAdd = it->first > node ? it->second : -it->second;
				Dist[it->first] = Dist[node] + toAdd;

				if (it->first == Y)
					return;
			}
	}
}

int main()
{
	readData();
	solve();
	printData();
	dealloc();

	//system("pause");
	return 0;
}