Pagini recente » Cod sursa (job #1158752) | Cod sursa (job #2852729) | Cod sursa (job #2676730) | Cod sursa (job #2961526) | Cod sursa (job #3271884)
#include<iostream>
#include<fstream>
#include<vector>
#include<cstring>
#include<queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int NMAX=50005;
const int MMAX=250007;
const int INF=1000000009;
int n,m,a,b,c,i;
int cost[NMAX];
bool change=0;
bool good;
struct ed
{
int x,y,w;
};
ed aux;
queue<int> q;
bool inn[NMAX];
vector<ed> adj[NMAX];
int rep[NMAX];
int main()
{
in>>n>>m;
for(i=1;i<=m;i++)
{
in>>a>>b>>c;
aux.x=a;
aux.y=b;
aux.w=c;
adj[a].push_back(aux);
}
memset(cost,INF,sizeof(cost));
cost[1]=0;
good=0;
q.push(1);
inn[1]=1;
while(!q.empty())
{
int node=q.front();
q.pop();
inn[node]=0;
for(auto g:adj[node])
{
if(cost[g.y]>cost[g.x]+g.w)
{
cost[g.y]=cost[g.x]+g.w;
if(inn[g.y]==0)
{
q.push(g.y);
}
rep[g.y]++;
if(rep[g.y]==n+1)
{
out<<"Ciclu negativ!";
return 0;
}
}
}
}
for(i=2;i<=n;i++)
{
out<<cost[i]<<" ";
}
}