Pagini recente » Cod sursa (job #1396829) | Cod sursa (job #1978208) | Cod sursa (job #375283) | Cod sursa (job #1505535) | Cod sursa (job #2807596)
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");
const int INF = 1e9;
vector<pair<int,int>> la[50005];
int dist[50005];
int viz[50005];
int n,m;
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] = INF;
dist[1] = 0;
priority_queue <pair<int,int>> pq;
pq.push({0, 1});
while (pq.size())
{
int from = pq.top().second;
viz[from] ++;
if(viz[from] >= n)
{
g<< "Ciclu negativ!";
return 0;
}
pq.pop(); //il scoate inainte sa se uite la vecinii lui
for (auto& per: la[from])
{
int to = per.first;
int cost = per.second;
if (dist[to] > dist[from] + cost)
{
dist[to] = dist[from] + cost;
pq.push({-dist[to], to});
}
}
}
for (int i = 2; i <= n; i++)
{
if (INF == dist[i]) //daca nu exista drum se considera distanta 0
dist[i] = 0;
g<< dist[i] << ' ';
}
return 0;
}