Pagini recente » Cod sursa (job #1362060) | Cod sursa (job #2138627) | Cod sursa (job #3279520) | Cod sursa (job #98035) | Cod sursa (job #2505676)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <climits>
using namespace std;
int n,m,cost[50005],a[50005],ok[50005],ceva=1;
vector<pair<int,int> >g[50005];
queue<int>q;
void citire()
{
ifstream fin("bellmanford.in");
fin>>n>>m;
int x,y,c;
for(int i=0;i<m;i++)
{
fin>>x>>y>>c;
g[x].push_back(make_pair(y,c));
}
for(int i=2;i<=n;i++)
cost[i]=INT_MAX/2;
cost[1]=0;
}
void bf()
{
q.push(1);
ok[1]=1;
a[1]=1;
while(!q.empty())
{
int c=q.front();
q.pop();
ok[c]=0;
for(auto &v:g[c])
if(cost[v.first]>cost[c]+v.second)
{
cost[v.first]=cost[c]+v.second;
if(!ok[v.first])
{
a[v.first]++;
if(a[v.first]>=n)
{
ceva=0;
return;
}
q.push(v.first);
ok[v.first]=1;
}
}
}
}
void afisare()
{
ofstream fout("bellmanford.out");
if(!ceva)
{
fout<<"Ciclu negativ!";
return;
}
for(int i=1;i<=n;i++)
if(a[i]>=n)
{
fout<<"Ciclu negativ!";
return;
}
for(int i=2;i<=n;i++)
fout<<cost[i]<<" ";
}
int main()
{
citire();
bf();
afisare();
return 0;
}