Pagini recente » Cod sursa (job #2015103) | Cod sursa (job #1780860) | Cod sursa (job #1031180) | Cod sursa (job #1285333) | Cod sursa (job #1839487)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ofstream fout("dijkstra.out");
const int Inf = 0x3f3f3f3f;
using PII = pair<int, int>;
using VI = vector<int>;
vector<vector<PII>> G;
int n;
VI d;
void Read();
void Dijkstra(int x, VI& d);
int main()
{
Read();
Dijkstra(1, d);
for (int x = 2; x <= n; ++x)
if (d[x] != Inf)
fout << d[x] << ' ';
else
fout << 0 << ' ';
fout.close();
}
void Dijkstra(int x, VI& d)
{
d = VI(n + 1, Inf);
priority_queue<PII, vector<PII>, greater<PII>> Q; // min-heap
d[x] = 0;
int dx, w, y;
for (Q.push({0, x}); !Q.empty();)
{
x = Q.top().second, dx = Q.top().first;
if ( dx > d[x] )
continue;
for (auto& p : G[x])
{
y = p.second; w = p.first;
if ( d[y] > d[x] + w )
{
d[y] = d[x] + w;
Q.push({d[y], y});
}
}
if ( Q.top().first == dx && Q.top().second == x )
Q.pop();
}
}
void Read()
{
ifstream fin("dijkstra.in");
int m, x, y, w;
fin >> n >> m;
//G.resize(n + 1);
G = vector<vector<PII>>(n + 1);
while (m--)
{
fin >> x >> y >> w;
G[x].push_back({w, y});
}
fin.close();
}