Pagini recente » Cod sursa (job #3254963) | Cod sursa (job #2397258) | Cod sursa (job #1861882) | Cod sursa (job #1664497) | Cod sursa (job #2502852)
//#include "pch.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
#include <queue>
using namespace std;
struct Node {
int number, value;
bool operator<(const Node& rhs) const
{
return value > rhs.value;
}
};
int MAX = 1 << 30;
vector<pair<int,int>> graph[50001];
bool searched[50001];
int distanceValues[50001];
void AddNewNode(int x, int y, int cost) {
graph[x].push_back(make_pair(cost,y));
}
void Dijktra(int startNode, int n) {
priority_queue<Node> queue;
Node newNode;
newNode.number = startNode;
newNode.value = 0;
queue.push(newNode);
distanceValues[startNode] = 0;
while (queue.size() > 0) {
int node = queue.top().number;
queue.pop();
searched[node] = true;
for (pair<int,int> x : graph[node])
{
if (searched[x.second] == true)continue;
if ((distanceValues[node] + x.first) < distanceValues[x.second]) {
distanceValues[x.second] = distanceValues[node] + x.first;
}
Node node;
node.number = x.second;
node.value = distanceValues[x.second];
queue.push(node);
}
}
}
int main()
{
int n, m, x, y, cost;
int startNode = 1;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
f >> n >> m;
for (int i = 1; i <= n; ++i) {
searched[i] = false;
distanceValues[i] = MAX;
}
while (m--) {
f >> x >> y >> cost;
AddNewNode(x, y, cost);
}
Dijktra(startNode, n);
for (int i = 2; i <= n; ++i) {
if(distanceValues[i]!=MAX)
g << distanceValues[i] << " ";
else g << 0 << " ";
}
}