Pagini recente » Cod sursa (job #1761207) | Profil bozoncanca | Cod sursa (job #1821585) | Cod sursa (job #2752864) | Cod sursa (job #1370079)
#include <algorithm>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int N, M, x, y, c, D[50005], used[50005], inQ[50005];
vector < pair<int, int> > G[50005];
queue < int > Q;
int main()
{
f>>N>>M;
for (int i=1; i<=M; ++i)
{
f>>x>>y>>c;
G[x].push_back(make_pair(y, c));
}
for (int i=1; i<=N; ++i)
D[i]=(1<<30);
Q.push(1); D[1]=0;
while (Q.size())
{
int nod=Q.front(); Q.pop();
++used[nod]; inQ[nod]=0;
if (used[nod]==N)
{
g<<"Ciclu negativ\n"; return 0;
}
vector< pair<int, int> >::iterator it=G[nod].begin();
for (; it!=G[nod].end(); ++it)
if (D[nod]+it->second < D[it->first])
{
D[it->first]=D[nod]+it->second;
if (!inQ[it->first])
inQ[it->first]=1, Q.push(it->first);
}
}
for (int i=2; i<=N; ++i)
g<<D[i]<<' ';
return 0;
}