Pagini recente » Cod sursa (job #474752) | Cod sursa (job #2664734) | Cod sursa (job #2780124) | Cod sursa (job #233803) | Cod sursa (job #1766573)
#include <bits/stdc++.h>
#define Nmax 50005
#define INF (1 << 30)
using namespace std;
struct muchie
{
int nod, cost;
};
vector <muchie> L[Nmax];
bitset <Nmax> viz;
bool Negative;
int dist[Nmax], cnt[Nmax], n, m;
queue <int> q;
void Citire()
{
ifstream f("bellmanford.in");
f >> n >> m;
muchie w;
int x;
for(int i = 1; i <= n; i++)
{
f >> x >> w.nod >> w.cost;
L[x].push_back(w);
}
f.close();
}
void BellmanFord()
{
for(int i = 1; i <= n; i++)
dist[i] = INF;
dist[1] = 0;
viz[1] = 1;
cnt[1] = 1;
q.push(1);
while(!q.empty() && !Negative)
{
int nod = q.front();
q.pop();
viz[nod] = 1;
for(unsigned i = 0; i < L[nod].size(); i++)
{
int j = L[nod][i].nod;
int c = L[nod][i].cost;
if(dist[j] > dist[nod] + c)
{
dist[j] = dist[nod] + c;
if(!viz[j])
{
q.push(j);
viz[j] = 1;
cnt[j]++;
if(cnt[j] > n)
Negative = true;
}
}
}
}
}
void Afisare()
{
ofstream g("bellmanford.out");
if(Negative)
g << "Ciclu negativ!";
else
for(int i = 2; i <= n; i++)
g << dist[i] << " ";
g << "\n";
g.close();
}
int main()
{
Citire();
BellmanFord();
Afisare();
return 0;
}