Pagini recente » Cod sursa (job #808977) | Cod sursa (job #2293315) | Cod sursa (job #2422277) | Cod sursa (job #1626947) | Cod sursa (job #3260675)
#include <iostream>
#include <fstream>
#include <map>
#include <queue>
#include <vector>
#define INF (1LL << 31)
using namespace std;
struct Edge {
int from;
int to;
long long weight;
bool operator < (const Edge& b) {
return this->weight > b.weight;
}
};
map<int, vector<Edge>> graph;
priority_queue<Edge> q;
map<int, long long> dist;
void dijkstra(int s, int n) {
queue<Edge> q;
for(int i = 1; i <= n; i++)
dist[i] = INF;
q.push({0, s, 0LL});
dist[0] = 0LL;
while(!q.empty()) {
Edge top = q.front();
q.pop();
if(dist[top.to] > top.weight) {
dist[top.to] = top.weight;
for(Edge next : graph[top.to])
q.push({next.from, next.to, next.weight+dist[next.from]});
}
}
}
int main() {
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int i, j, n, m, to, from;
long long weight;
fin>>n>>m;
for(int i = 0; i < m; i++) {
fin>>from>>to;
fin>>weight;
graph[from].push_back({from, to, weight});
}
dijkstra(1, n);
for(int i = 2; i <= n; i++) {
if(dist[i] == INF)
dist[i] = 0LL;
fout<<dist[i]<<" ";
}
return 0;
}