Pagini recente » Cod sursa (job #3256599) | Cod sursa (job #2041011) | Cod sursa (job #2488901) | Cod sursa (job #2832926) | Cod sursa (job #2535855)
#include <iostream>
#include <fstream>
#include <set>
#include <vector>
#include <cstring>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
#define INF 0x7f7f7f7f
int n, m;
vector<pair<int, int> > nod[50010];
set<pair<int, int> > s;
int dist[50010];
void readAndSet() {
fin >> n >> m;
for (int i = 1; i <= m; i++) {
int a, b, cost;
fin >> a >> b >> cost;
nod[a].push_back(make_pair(b, cost));
nod[b].push_back(make_pair(a, cost));
}
}
void dijkstra() {
memset(dist, INF, sizeof dist);
s.insert(make_pair(1, 0));
while (!s.empty()) {
int from = s.begin()->first;
int actCost = s.begin()->second;
s.erase(s.begin());
for (pair<int, int> way : nod[from]) {
int to = way.first;
int addCost = way.second;
if (actCost + addCost < dist[to]) {
if (s.find(make_pair(to, dist[to])) != s.end())
s.erase(s.find(make_pair(to, dist[to])));
s.insert(make_pair(to, actCost + addCost));
dist[to] = actCost + addCost;
}
}
}
}
void printDist() {
for (int i = 2; i <= n; i++)
if (dist[i] == INF)
fout << 0;
else
fout << dist[i] << ' ';
}
int main() {
readAndSet();
dijkstra();
printDist();
return 0;
}