Cod sursa(job #1442640)

Utilizator tweetyMarinescu Ion tweety Data 25 mai 2015 22:47:44
Problema Sate Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.71 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;
bool* InQueue;
int NodesNo;
int EdgesNo;
int X;
int Y;

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

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

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

void readData()
{
	In >> NodesNo >> EdgesNo >> X >> Y;
	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 - 1] << " ";

	Out.close();
}

bool isInQueue(const int& node)
{
	return InQueue[node] == true;
}

void addToQueue(const int& node)
{
	Queue.push(node);
	InQueue[node] = true;
}

int removeFromQueue()
{
	int node = Queue.front();
	Queue.pop();
	InQueue[node] = false;

	return node;
}

void solve()
{
	Dist[X - 1] = 0;
	addToQueue(X - 1);

	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 - 1)
					return;
			}
	}
}

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

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