Pagini recente » Cod sursa (job #2687470) | Cod sursa (job #2059218) | Cod sursa (job #1794435) | Cod sursa (job #2180651) | Cod sursa (job #3005014)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int maxint=1000000000;
int ciclu[100001],viz[100001],n,m,s;
bool ok;
vector<int> G[100001],C[100001];
queue<int> q;
void bf(int x)
{
viz[x]=0;
q.push(x);
while(!q.empty())
{
int xc=q.front();
ciclu[xc]++;
if(ciclu[xc]>n)
{
ok=1;
fout << "Ciclu negativ!";
return;
}
for(int i=0;i<G[xc].size();i++)
{
int nod=G[xc][i];
int cost=C[xc][i];
if(viz[nod]>viz[xc]+cost)
{
viz[nod]=viz[xc]+cost;
q.push(nod);
}
}
q.pop();
}
}
int main()
{
fin >> n >> m;
for(int i=1;i<=m;i++)
{
int x,y,c;
fin >> x >> y >> c;
G[x].push_back(y);
C[x].push_back(c);
}
for(int i=1;i<=n;i++)
viz[i]=maxint;
bf(1);
if(!ok)
{
for(int i=2;i<=n;i++)
fout << viz[i] << " ";
}
return 0;
}