Pagini recente » Cod sursa (job #2539497) | Cod sursa (job #530610) | Cod sursa (job #1144594) | Cod sursa (job #3242320) | Cod sursa (job #2303593)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define MAX 1000000000
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
queue<int>q;
vector<pair<int, int> >graph[50005];
int n, m, from, to, cost, in_queue[50005], numbered[50005], dp[50005];
void solve()
{
q.push(1);
in_queue[1]=1;
numbered[1]=1;
while (!q.empty())
{
int element=q.front();
q.pop();
in_queue[element]=0;
for (auto &v:graph[element])
{
if (dp[v.first]>dp[element]+v.second)
{
dp[v.first]=dp[element]+v.second;
if (in_queue[v.first]==0)
{
in_queue[v.first]=1;
q.push(v.first);
numbered[v.first]++;
if (numbered[v.first]>n)
{
g << "Ciclu negativ!";
return;
}
}
}
}
}
for (int i=2; i<=n; i++)
{
g << dp[i] <<' ';
}
}
int main()
{
f >> n >> m;
for (int i=1; i<=m; i++)
{
f >> from >> to >> cost;
graph[from].push_back(make_pair(to,cost));
}
for (int i=2; i<=n; i++)
{
dp[i]=MAX;
}
solve();
return 0;
}