Pagini recente » Cod sursa (job #2949361) | Cod sursa (job #2739288) | Cod sursa (job #606186) | Cod sursa (job #1062429) | Cod sursa (job #1469103)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
const int nmax = 50005;
vector < pair<int,int> > graf[nmax];
int n, m, d[nmax], nrq[nmax];
bool viz[nmax];
void bellmanford()
{
int i, nod;
queue <int> q;
vector <pair<int,int> >::iterator it;
for(i=2; i<=n; i++)
d[i]=1<<30;
q.push(1);
while(!q.empty())
{
nod=q.front();
q.pop();
viz[nod]=false;
for(it=graf[nod].begin(); it!=graf[nod].end(); it++)
if(d[it->first] > d[nod]+it->second)
{
d[it->first]=d[nod]+it->second;
if(!viz[it->first])
{
if(nrq[it->first]>n)
{
fout << "Ciclu negativ!";
return;
}
nrq[it->first]++;
viz[it->first]=true;
q.push(it->first);
}
}
}
for(i=2; i<=n; i++)
fout << d[i] << " ";
}
int main()
{
int x, y, c, i;
fin >> n >> m;
for(i=1; i<=m; i++)
{
fin >> x >> y >> c;
graf[x].push_back(make_pair(y, c));
}
bellmanford();
fin.close();
fout.close();
return 0;
}