Pagini recente » Cod sursa (job #2916977) | Cod sursa (job #3219526)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <cstring>
#define MAX_NODES 50000
#define INF 0x7f7f7f7f
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
vector<pair<int, int>> directedGraph[MAX_NODES + 1];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> ascendingDistance;
int distances[MAX_NODES + 1];
bitset<MAX_NODES + 1> isVisited;
void getAllMinDistancesFromStartNode(int startNode) { // a.k.a. Dijsktra
memset(distances, INF, sizeof distances);
distances[startNode] = 0;
ascendingDistance.push({ 0, startNode });
while (!ascendingDistance.empty()) {
pair<int, int> currentInformation = ascendingDistance.top();
int sourceNode = currentInformation.second; // note that we do not need an aditional variable for storing the cost of the current node, as we can access it directly through: distances[sourceNode]
ascendingDistance.pop();
if (!isVisited[sourceNode]) {
int nrNeighbours = directedGraph[sourceNode].size();
for (int i = 0; i < nrNeighbours; ++i) {
int neighbour = directedGraph[sourceNode][i].first;
int neighbourCost = directedGraph[sourceNode][i].second;
if (distances[sourceNode] + neighbourCost < distances[neighbour]) {
distances[neighbour] = distances[sourceNode] + neighbourCost;
ascendingDistance.push({ distances[neighbour], neighbour });
}
}
isVisited[sourceNode] = true;
}
}
}
void printMinimalDistances(int nrNodes) {
for (int node = 2; node <= nrNodes; ++node) {
if (isVisited[node]) {
fout << distances[node] << ' ';
} else {
fout << 0 << ' ';
}
}
}
int main() {
int nrNodes, nrDirectedEdges;
fin >> nrNodes >> nrDirectedEdges;
for (int i = 1; i <= nrDirectedEdges; ++i) {
int sourceNode, destinationNode, distance;
fin >> sourceNode >> destinationNode >> distance;
directedGraph[sourceNode].push_back({ destinationNode, distance });
}
getAllMinDistancesFromStartNode(1);
printMinimalDistances(nrNodes);
return 0;
}