Pagini recente » Cod sursa (job #2049283) | Cod sursa (job #3148218) | Cod sursa (job #2002095) | Cod sursa (job #1281267) | Cod sursa (job #3309915)
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 50002
#define INF (1<<30)
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int N,M,ok;
vector<int> cost(NMAX,INF),in_queue(NMAX,0),f(NMAX,0);
vector<pair<int,int>> graph[NMAX];
queue<int>q;
void citire()
{
fin>>N>>M;
int a,b,c;
for(int i=1; i<=M; i++)
{
fin>>a>>b>>c;
graph[a].push_back({b,c});
}
}
void BFS()
{
cost[1]=0;
q.push(1);
f[1]=in_queue[1]=1;
while(!q.empty())
{
int nod=q.front();
in_queue[nod]=0;
q.pop();
for(int i=0; i<graph[nod].size(); i++)
{
int next_nod=graph[nod][i].first;
if(cost[next_nod]>cost[nod]+graph[nod][i].second)
{
cost[next_nod]=cost[nod]+graph[nod][i].second;
f[next_nod]++;
if(f[next_nod]>N)
{
ok=1;
return;
}
if(!in_queue[next_nod])
{
in_queue[next_nod]=1;
q.push(next_nod);
}
}
}
}
}
int main()
{
citire();
ok=0;
BFS();
if(ok)
{
fout<< "Ciclu negativ!" << "\n";
return 0;
}
for(int i=2; i<=N; i++)
{
fout<< cost[i] << " ";
}
fout<< "\n";
return 0;
}