Pagini recente » Cod sursa (job #297497) | Cod sursa (job #3287159) | Cod sursa (job #686403) | Cod sursa (job #2093394) | Cod sursa (job #2796290)
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define pf push_front
#define MOD 1000000007
#define NMAX 50005
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
struct A
{
int y, cost;
};
vector < A > v[NMAX];
queue < int > q;
int main()
{
ios_base::sync_with_stdio(false), cin.tie(0),cout.tie(0);
int n, m, x, y, z, i, nr[NMAX], r[NMAX];
bool viz[NMAX];
fin >> n >> m;
while(m--)
{
fin >> x >> y >> z;
v[x].pb({y, z});
}
for(i = 1; i <= n; i++) viz[i] = 0, nr[i] = 0, r[i] = INT_MAX;
r[1] = 0, viz[1] = 1, q.push(1);
while(q.empty() == 0)
{
x = q.front(), q.pop();
viz[x] = 0;
nr[x]++;
if(nr[x] == n - 3)
{
fout << "Ciclu negativ!";
break;
}
else for(auto it:v[x])
if(r[x] + it.cost < r[it.y])
{
r[it.y] = r[x] + it.cost;
if(viz[it.y] == 0) q.push(it.y);
}
}
if(nr[x] != n) for(i = 2; i <= n; i++) fout << r[i] << ' ';
return 0;
}