Pagini recente » Cod sursa (job #3228576) | Cod sursa (job #733453) | Cod sursa (job #920162) | Cod sursa (job #276388) | Cod sursa (job #2027201)
#include <fstream>
#include <queue>
#include <vector>
#define VAL 50005
#define INF 1000000000
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int N, M, i, j, a, b, c;
int dp[VAL], nr[VAL], nod;
bool ap[VAL], ok;
vector < pair <int, int> > G[VAL];
vector < pair <int, int> > :: iterator it;
queue <int> Q;
void BellmanFord()
{
Q.push(1);
nr[1]=1;
ap[1]=true;
while (Q.empty()==false)
{
nod=Q.front();
Q.pop();
for (it=G[nod].begin(); it!=G[nod].end(); it++)
{
if (dp[it->first]>dp[nod]+it->second)
{
dp[it->first]=dp[nod]+it->second;
if (ap[it->first]==false)
{
ap[it->first]=true;
nr[it->first]++;
if (nr[it->first]==N-1)
{
ok=true;
return;
}
Q.push(it->first);
}
}
}
}
ap[nod]=false;
}
int main()
{
fin >> N >> M;
for (i=1; i<=M; i++)
{
fin >> a >> b >> c;
G[a].push_back(make_pair(b, c));
}
for (i=2; i<=N; i++)
dp[i]=INF;
BellmanFord();
if (ok==true)
fout << "Ciclu negativ!";
else
for (i=2; i<=N; i++)
fout << dp[i] << " ";
fin.close();
fout.close();
return 0;
}