Mai intai trebuie sa te autentifici.
Cod sursa(job #3323855)
| Utilizator | Data | 20 noiembrie 2025 08:36:02 | |
|---|---|---|---|
| Problema | Algoritmul lui Dijkstra | Scor | 0 |
| Compilator | cpp-64 | Status | done |
| Runda | Arhiva educationala | Marime | 1.24 kb |
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int n, m, dp[50552], viz[50005];
const int INF = 1e9;
vector<pair<int, int>> a[50002];
void Djk(int start)
{
priority_queue<pair<int, int>> q;
for (int i = 1; i <= n; i++)
{
dp[i] = INF;
viz[i] = 0;
}
dp[start] = 0;
viz[start] = 1;
q.push({0, start});
while (!q.empty())
{
int nod = q.top().second;
q.pop();
for (auto w : a[nod]) // w.first e nodul, w.second e costul (pozitiv)
if (!viz[w.first] && dp[nod] + w.second < dp[w.first])
{
dp[w.first] = dp[nod] + w.second;
q.push({-dp[w.first], w.first});
viz[w.first] = 1;
}
}
}
int main()
{
fin >> n >> m;
int x, y, c;
for (int i = 1; i <= m; i++)
{
fin >> x >> y >> c;
a[x].push_back({y, c});
// a[y].push_back({x, c});
}
Djk(1);
for (int i = 2; i <= n; i++)
if (dp[i] != INF)
fout << dp[i] << ' ';
else
fout << "0 ";
fout << '\n';
return 0;
}