Pagini recente » Cod sursa (job #2239109) | Cod sursa (job #3187306) | Cod sursa (job #3248283) | Cod sursa (job #2343811) | Cod sursa (job #2505620)
#include <bits/stdc++.h>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
queue<int>q;
vector<pair<int,int> >graph[50005];
const int MOD = 1000;
int n, m, from, to, cost;
int nr_update[50005], mini[50005];
bool in_queue[50005];
void solve()
{
q.push(1);
nr_update[1]=1;
int sus;
while (!q.empty())
{
sus=q.front();
in_queue[sus]=0;
if (nr_update[sus]==n)
{
g << "Ciclu negativ!";
return;
}
q.pop();
for (auto &v:graph[sus])
{
if (mini[v.first]>mini[sus]+v.second)
{
if (!in_queue[v.first])
q.push(v.first), in_queue[v.first]=1;
nr_update[v.first]++;
mini[v.first]=mini[sus]+v.second;
}
}
}
for (int i=2; i<=n; ++i)
g << mini[i] <<' ';
}
int main()
{
f >> n >> m;
for (int i=1; i<=m; ++i)
{
f >> from >> to >> cost;
graph[from].push_back({to,cost});
}
for (int i=2; i<=n; ++i)
mini[i]=0x3f3f3f3f;
solve();
return 0;
}