Pagini recente » Cod sursa (job #3197530) | Cod sursa (job #922661) | Cod sursa (job #741048) | Cod sursa (job #2217808) | Cod sursa (job #1747162)
#include <bits/stdc++.h>
#define Nmax 50005
#define INF 1000000000
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
struct muchie
{
int nod, cost;
};
vector <muchie> L[Nmax];
bool viz[Nmax], Negativ;
int d[Nmax], cnt[Nmax];
queue <int> q;
int n, m;
void BellmanFord()
{
int j, c, i, nod, len;
while(!q.empty() && !Negativ)
{
nod = q.front();
q.pop();
viz[nod] = false;
len = L[nod].size();
for(i = 0; i < len; ++i)
{
j = L[nod][i].nod;
c = L[nod][i].cost;
if(d[j] > d[nod] + c)
{
d[j] = d[nod] + c;
if(!viz[j])
{
q.push(j);
viz[j] = true;
cnt[j]++;
if(cnt[j] > n)
Negativ = true;
}
}
}
}
}
int main()
{
int i, nod;
muchie w;
fin >> n >> m;
for(i = 1; i <= m; i++)
{
fin >> nod >> w.nod >> w.cost;
L[nod].push_back(w);
}
for(i = 1;i <= n; i++)
d[i] = INF;
d[1] = 0;
viz[1] = true;
cnt[1] = 1;
q.push(1);
BellmanFord();
if(Negativ)
fout << "Ciclu negativ!";
else
{
for(i = 2; i <= n; ++i)
fout << d[i] << " ";
fout << "\n" ;
}
return 0;
}