Mai intai trebuie sa te autentifici.
Cod sursa(job #2980969)
Utilizator | Data | 16 februarie 2023 23:34:06 | |
---|---|---|---|
Problema | Algoritmul lui Dijkstra | Scor | 100 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 1.08 kb |
#include <iostream>
#include <fstream>
#include <cstring>
#include <algorithm>
#include <climits>
#include <vector>
#include <cmath>
#include <queue>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int inf = 1e9;
int n, m;
struct elem {
int nod, cost;
bool operator<(const elem& b)const {
return cost > b.cost;
}
};
priority_queue<elem>q;
vector<elem>g[50005];
int d[50005];
int main()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, c;
fin >> x >> y >> c;
g[x].push_back({ y,c });
}
for (int i = 1; i <= n; i++)
d[i] = inf;
d[1] = 0;
q.push({ 1,0 });
while (!q.empty())
{
int nod = q.top().nod;
int cost = q.top().cost;
q.pop();
if (cost != d[nod])
continue;
for(elem i:g[nod])
if (d[nod] + i.cost < d[i.nod])
{
d[i.nod] = d[nod] + i.cost;
q.push({ i.nod,d[i.nod] });
}
}
for (int i = 2; i <= n; i++)
if (d[i] == inf)
fout << 0 << ' ';
else
fout << d[i] << ' ';
return 0;
}