Pagini recente » Cod sursa (job #926134) | Cod sursa (job #915845) | Cod sursa (job #1460951) | Cod sursa (job #1387692) | Cod sursa (job #2272532)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
#define pii pair<int,int>
#define x first
#define y second
#define pb push_back
const int Nmax = 50000 + 5;
vector<pii>v[Nmax];
queue<pii>Q;
bool inq[Nmax];
int n, m, viz[Nmax], dp[Nmax];
int main()
{
fin >> n >> m;
for(int i = 1,a, b, cst; i <= m; ++i)
{
fin >> a >> b >> cst;
v[a].pb({b, cst});
}
for(int i = 2; i <= n; ++i)dp[i] = (1<< 30);
Q.push({1, 0}); inq[1] = 1; viz[1] = 1;
while(!Q.empty())
{
int nod = Q.front().x;
int cost = Q.front().y;
inq[nod] = 0;viz[nod] ++;
if(viz[nod] == n)
{
fout << "Ciclu negativ";
return 0;
}
Q.pop();
for(auto i : v[nod])
{
if(dp[i.x] > dp[nod] + i.y)
{
dp[i.x] = dp[nod] + i.y;
if(!inq[i.x])
{
Q.push({i.x, dp[i.x]});
inq[i.x] = 1;
}
}
}
}
for(int i = 2; i <= n; ++i)
if(dp[i] != (1<< 30))fout << dp[i] << ' ';
else fout << -1 << ' ';
return 0;
}