Pagini recente » Cod sursa (job #1715330) | Cod sursa (job #1706957) | Cod sursa (job #758228) | Cod sursa (job #1685121) | Cod sursa (job #2354693)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int N = 50001;
const int M = 250001;
const int INF = 1001;
int n, m, x, y, c, d[N], nrq[N];
bool inq[N];
vector < pair<int, int> > a[N];
queue <int> q;
int main()
{
in>>n>>m;
for(int i=1; i<=m; i++)
{
in>>x>>y>>c;
a[x].push_back(make_pair(y, c));
}
for(int i=1; i<=n; i++)
d[i] = INF;
q.push(1);
inq[1] = true;
nrq[1]++;
d[1] = 0;
pair<int, int> p;
while(!q.empty())
{
x = q.front();
q.pop();
inq[x] = false;
//for(auto p: a[x])
for (int i = 0; i < a[x].size(); i++)
{
p = a[x][i];
y = p.first;
c = p.second;
if(d[x] + c < d[y])
{
d[y] = d[x] + c;
if(!inq[y])
{
q.push(y);
inq[y] = true;
nrq[y]++;
if(nrq[y] > n)
{
out<<"Ciclu negativ!";
return 0;
}
}
}
}
}
for(int i=2; i<=n; i++)
out<<d[i]<<' ';
return 0;
}