Pagini recente » Cod sursa (job #2790522) | Cod sursa (job #1356357) | Cod sursa (job #1687335) | Cod sursa (job #1898969) | Cod sursa (job #3325002)
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using std::vector, std::pair;
int main(){
std::ifstream in("dijkstra.in");
std::ofstream out("dijkstra.out");
int n, m;
in >> n >> m;
vector<vector<pair<int, int>>> graph(n, vector<pair<int, int>>()); // graph[u][x] = {v, w}: u -> v, w értek
std::priority_queue<pair<int, int>, vector<pair<int, int>>, std::greater<pair<int, int>>> q; // q.front().first hova, q.front().second jelenleg milyen drága
vector<int> distance(n, INT_MAX);
distance[0] = 0;
q.push({distance[0], 0});
while(m--){
int u, v, w;
in >> u >> v >> w;
u--; v--;
graph[u].push_back({v, w});
}
while(!q.empty()){
// u - honnan, v - hova, w - súly, d - jelenlegi távolság
int u = q.top().second, d = q.top().first;
q.pop();
if(d == distance[u]){
for(auto e : graph[u]){
int v = e.first, w = e.second;
if(distance[v] > d + w){
distance[v] = d + w;
q.push({distance[v], v});
}
}
}
}
for(int i = 1; i < n; i++)
if(distance[i] == INT_MAX)
out << 0 << ' ';
else
out << distance[i] << ' ';
}