Pagini recente » Cod sursa (job #1104600) | Cod sursa (job #780868) | Cod sursa (job #1342931) | Istoria paginii utilizator/oltean_florin | Cod sursa (job #2037334)
#include <iostream>
#include <vector>
#include <list>
#include <queue>
#include <stdio.h>
#include <string.h>
#include <climits>
#include <set>
const int maxn = 50001;
const int inf = 1 << 30;
FILE *in = fopen("dijkstra.in","r"), *out = fopen("dijkstra.out","w");
using namespace std;
class Graph
{
public:
std::list<std::pair<int, int> >* neigh;
int n;
Graph(int n) {
neigh = new std::list<std::pair<int, int>> [n + 1];
this->n = n + 1;
}
void addEdge(int u, int v, int w) {
neigh[u].push_back(make_pair(v, w));
}
void shortestPath(int source) {
set<pair<int, int>> pq;
vector<int> distance(n, INT_MAX -1);
vector<bool> visited(n, false);
distance[source] = 0;
visited[source] = true;
pq.insert(make_pair(0, source));
while(!pq.empty()) {
auto node = pq.begin()->second;
pq.erase(pq.begin());
//std::cout << "NOde " <<node << " " << distance[node] << "\n";
for (const auto& child : neigh[node]) {
auto neighbour = child.first;
auto weight = child.second;
if (distance[neighbour] > distance[node] + weight) {
if (visited[neighbour] ) {
//std::cout << "Search " <<neighbour << " " << distance[neighbour] << " " << "\n";
pq.erase(pq.find({distance[neighbour], neighbour}));
}
distance[neighbour] = distance[node] + weight;
visited[neighbour] = true;
//std::cout << "Insert " <<neighbour << " " << distance[neighbour] << "\n";
pq.insert({distance[neighbour], neighbour});
}
}
}
for ( int i = 2; i < n; ++i)
fprintf(out, "%d ", distance[i] == INT_MAX -1 ? 0 : distance[i]);
fprintf(out, "\n");
}
};
int main()
{
int n, m;
fscanf(in, "%d %d", &n, &m);
Graph g(n);
int x, y, z;
for ( int i = 0; i < m; ++i )
{
fscanf(in, "%d %d %d", &x, &y, &z);
g.addEdge(x, y, z);
}
g.shortestPath(1);
return 0;
}