Pagini recente » Cod sursa (job #2477761) | Cod sursa (job #1326248) | Cod sursa (job #1032350) | Cod sursa (job #2220562) | Cod sursa (job #2261636)
/* Algoritmul lui Dijkstra
* O(n^2)
*/
#include <fstream>
#include <vector>
#include <queue>
#include <set>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
using VI = vector<int>;
using VB = vector<bool>;
using PI = pair<int, int>;
using VVP = vector<vector<PI>>;
const int Inf = 0x3f3f3f3f;
VVP G;
VI d; // distantele minime de la sursa la celelalte noduri
int n, m;
void ReadGraph();
void Write();
void Dijkstra(int x, VI& d);
int main()
{
ReadGraph();
Dijkstra(1, d);
Write();
}
void Dijkstra(int x, VI& d) // O(n^2)
{
set<PI> Q; // coada de prioritati
d = VI(n + 1, Inf);
d[x] = 0;
int y, dx, w;
Q.insert({0, x});
while (!Q.empty())
{
x = Q.begin()->second;
dx = Q.begin()->first;
Q.erase(Q.begin());
if (dx > d[x])
continue;
for (auto& p : G[x])
{
y = p.first; w = p.second;
if (d[y] > d[x] + w)
{
d[y] = d[x] + w;
Q.insert({d[y], y});
}
}
}
}
void ReadGraph()
{
fin >> n >> m;
G = VVP(n + 1);
int x, y, w; // w - ponderea muchiei
while (m--)
{
fin >> x >> y >> w;
G[x].push_back({y, w});
}
}
void Write()
{
for (int i = 2; i <= n; ++i)
if (d[i] == Inf)
fout << 0 << ' ';
else
fout << d[i] << ' ';
}