Pagini recente » Cod sursa (job #2828493) | Cod sursa (job #765080) | Cod sursa (job #667357) | Cod sursa (job #870366) | Cod sursa (job #899690)
Cod sursa(job #899690)
#include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
#include <vector>
#include <queue>
using namespace std;
#define FORIT(it,v) for(typeof((v).begin())it=(v).begin();it!=(v).end();++it)
const int MAX_N = 50100;
const int INF = 1 << 30;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int N, M;
vector<pair<int, int> > graph[MAX_N];
int cost[MAX_N];
bool visited[MAX_N];
void read_input();
void dijkstra(int source);
void print_output();
int main() {
read_input();
dijkstra(1);
print_output();
return 0;
}
void read_input() {
fin >> N >> M;
for (int i = 1; i <= M; ++i) {
int a, b, c;
fin >> a >> b >> c;
graph[a].push_back(make_pair(b, c));
graph[b].push_back(make_pair(a, c));
}
}
struct HeapCmp {
bool operator() (const int& lhs, const int& rhs) {
return cost[lhs] < cost[rhs];
}
};
void dijkstra(int source) {
fill(cost, cost + N + 1, INF);
cost[source] = 0;
priority_queue<int, vector<int>, HeapCmp> heap;
heap.push(source);
while (!heap.empty()) {
int node = heap.top();
heap.pop();
if (!visited[node]) {
FORIT (it, graph[node]) {
if (cost[node] + it->second < cost[it->first]) {
cost[it->first] = cost[node] + it->second;
heap.push(it->first);
}
}
visited[node] = true;
}
}
}
void print_output() {
for (int i = 2; i <= N; ++i) {
fout << (cost[i] == INF ? 0 : cost[i]) << ' ';
}
}