Cod sursa(job #2116469)

Utilizator mircearoataMircea Roata Palade mircearoata Data 27 ianuarie 2018 17:43:19
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <fstream>
#include <vector>
#include <queue>
#include <string>

using namespace std;

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

struct nodeCost{
	int to;
	int cost;
	nodeCost()
	{
		cost = 0x3f3f3f3f;
	}
};

int n,m;
vector<nodeCost> node[50001];
auto cmp = [](const nodeCost & left, const nodeCost & right){ return left.cost>right.cost;};
priority_queue<nodeCost,vector<nodeCost>,decltype(cmp)> costs(cmp);

int cost[50001];

int main()
{
	in>>n>>m;
	for(int i = 1;i<=m;i++)
	{
		int x,y,c;
		in>>x>>y>>c;
		nodeCost nod;
		nod.cost=c;
		nod.to=y;
		node[x].push_back(nod);
	}
	for(int i = 2;i<=n;i++)
	{
		cost[i]=0x3f3f3f3f;
	}
	nodeCost nod;
	nod.to=1;
	nod.cost=0;
	costs.push(nod);
	while(!costs.empty())
	{
		nodeCost minn = costs.top();
		costs.pop();
		for(nodeCost nod : node[minn.to])
		{
			nodeCost newCost = minn;
			newCost.cost += nod.cost;
			newCost.to=nod.to;
			if(newCost.cost<cost[nod.to]){
				cost[nod.to]=newCost.cost;
				costs.push(newCost);
			}
		}
	}

	string printAnswer;
	for(int i = 2;i<=n;i++)
	{
		if(cost[i]==0x3f3f3f3f)
			printAnswer += "0 ";
		else
			printAnswer += to_string(cost[i]) + " ";
	}
	out << printAnswer;
	return 0;
}