Pagini recente » Cod sursa (job #1010695) | Cod sursa (job #2581731) | Cod sursa (job #1289591) | Cod sursa (job #391774) | Cod sursa (job #2176386)
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
#define nmax 50005
#define inf (INT_MAX-1)
vector<pair<int, int> > g[nmax];
queue<int> q;
int n, m, frQ[nmax], cNeg=0, dst[nmax];
bool inQ[nmax];
void citire()
{
int i, x, y, c;
fin>>n>>m;
for(i=1; i<=m; i++)
{
fin>>x>>y>>c;
g[x].push_back(make_pair(y, c));
}
fin.close();
}
void BellmanFord()
{
int i, k;
vector<pair<int, int>>::iterator it;
for(i=1; i<=n; i++)
dst[i]=inf;
dst[1]=0;
frQ[1]=1;
inQ[1]=1;
q.push(1);
while(!cNeg && !q.empty())
{
k=q.front();
q.pop();
inQ[k]=0;
for(it=g[k].begin(); it!=g[k].end(); it++)
if(dst[k]<inf && dst[it->first]>dst[k]+it->second)
{
dst[it->first]=dst[k]+it->second;
if(!inQ[it->first])
{
inQ[it->first]=1;
frQ[it->first]++;
q.push(it->first);
if(frQ[it->first]>n)
cNeg=1;
}
}
}
}
void afisare()
{
if(cNeg)
fout<<"Ciclu negativ!";
else for(int i=2; i<=n; i++)
fout<<dst[i]<<' ';
fout<<'\n';
fout.close();
}
int main()
{
citire();
BellmanFord();
afisare();
return 0;
}