Pagini recente » Cod sursa (job #1115013) | Cod sursa (job #2887609) | Cod sursa (job #757156) | Cod sursa (job #2492474) | Cod sursa (job #887112)
Cod sursa(job #887112)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in ("bellmanford.in");
ofstream out("bellmanford.out");
int const N=50005;
int const MAXI=100000;
vector <int> v[N],c[N];
bool inq[N];
int n,m,cost[N],nrq[N];
void citire()
{
in>>n>>m;
int x,y,z;
for(int i=1;i<=m;i++)
{
in>>x>>y>>z;
v[x].push_back(y);
c[x].push_back(z);
}
}
void init()
{
for(int i=2;i<=n;i++)
cost[i]=MAXI;
}
bool bfs(int x)
{
queue <int> q;
q.push(x);
inq[x]=true;
nrq[x]++;
int y,z;
while(!q.empty())
{
x=q.front();
q.pop();
inq[x]=false;
for(int i=0;i<v[x].size();i++)
{
y=v[x][i]; z=c[x][i];
if(cost[y]>cost[x]+z)
{
cost[y]=cost[x]+z;
if(!inq[y])
{
q.push(y);
inq[y]=true;
nrq[y]++;
if(nrq[y]==n) return true;
}
}
}
}
return false;
}
int main()
{
citire();
init();
if(bfs(1)){out<<"Ciclu negativ!\n";return 0;}
for(int i=2;i<=n;i++)
out<<cost[i]<<" ";
out<<"\n";
return 0;
}