Pagini recente » Cod sursa (job #2213876) | Cod sursa (job #2142002) | Cod sursa (job #2279134) | Cod sursa (job #1544305) | Cod sursa (job #2794474)
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n,m;
vector<pair<int,int>> la[50001];
int dist[50005];
int dijkstra(int s)
{
dist[s] = 0;
priority_queue<pair<int,int>> pq;
pq.push({0, s});
int iteratii = 0;
while (pq.size())
{
pair<int,int> top = pq.top(); // top second este nodul ale carui muchii le vom parcurge acum, top first este costul de a ajunge la el
pq.pop();
if (dist[top.second] != (-1) * top.first) // daca distanta retinuta in pq este diferita de distanta curenta pt nodul din pq, inseamna ca deja am modificat distanta printr-un alt nod si am adaugat alta pereche pentru nodul curent
continue;
for (auto el: la[top.second])
{
if (dist[el.first] > dist[top.second] + el.second)
{
dist[el.first] = dist[top.second] + el.second;
pq.push({-el.second, el.first});
}
}
iteratii ++;
if (iteratii > n)
return -1;
}
return 0;
}
int main()
{
f >> n >> m;
for (int i = 0; i < m; i++)
{
int x,y,d;
f >> x >> y >> d;
la[x].push_back({y,d});
}
for (int i = 1; i <= n; i++)
dist[i] = 1000000000;
int st = dijkstra(1);
if (st == -1)
{
g << "Ciclu negativ!";
return 0;
}
for (int i = 2; i <= n; i++)
g << dist[i] << ' ';
return 0;
}