Pagini recente » Cod sursa (job #1927879) | Cod sursa (job #1183898) | Cod sursa (job #1645688) | Cod sursa (job #331614) | Cod sursa (job #2037306)
#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));
//std::cout << u << " " << v << " " << w << "\n";
}
void shortestPath(int source) {
const auto comparator = [](pair<int, int> a, pair<int, int> b) {
return a.second > b.second;
};
set<pair<int, int>, decltype(comparator)> pq(comparator);
vector<int> distance(n, INT_MAX -1);
vector<bool> visited(n, false);
distance[source] = 0;
visited[source] = true;
pq.insert(make_pair(source, 0));
while(!pq.empty()) {
auto node = *pq.begin();
pq.erase(pq.begin());
for (const auto& child : neigh[node.first]) {
//std::cout << "Getting : " << child.first << " " << distance[child.first] << distance[node.first] << " " << child.second <<"\n";
if (distance[child.first] > distance[node.first] + child.second) {
distance[child.first] = distance[node.first] + child.second;
//std::cout << "Updated : " << child.first << " " << distance[child.first] <<"\n";
if (visited[child.first]) {
for (auto it = pq.begin(); it != pq.end(); ++it) {
if (it->first == child.first) {
pq.erase(it);
}
}
}
visited[child.first] = true;
pq.insert(make_pair(child.first, distance[child.first]));
}
}
}
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;
}