Pagini recente » Cod sursa (job #430768) | Cod sursa (job #1958246) | Cod sursa (job #2127226) | Cod sursa (job #940098) | Cod sursa (job #1131687)
#include <fstream>
#include <vector>
#include <queue>
const int NMAX = 50003;
const int INF = 0x3f3f3f3f;
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n,m,x,y,cost,sol[NMAX],contor[NMAX],nod;
bool inqueue[NMAX],ok;
vector <int> G[NMAX];
queue <int> Q;
int main()
{
f >> n >> m;
for (int i = 1; i <= m; ++i)
{
f >> x >> y >> cost;
G[x].push_back(y);
G[x].push_back(cost);
}
for (int i = 1; i <= n; ++i)
{
sol[i] = INF;
}
sol[1] = 0;
Q.push(1);
inqueue[1] = true;
ok = true;
while (!Q.empty() && ok)
{
nod = Q.front();
Q.pop();
inqueue[nod] = false;
for (int i = 0; i < G[nod].size(); i+=2)
{
if (sol[nod] + G[nod][i+1] < sol[G[nod][i]])
{
sol[G[nod][i]] = sol[nod] + G[nod][i+1];
if (!inqueue[G[nod][i]])
{
contor[G[nod][i]]++;
if (contor[G[nod][i]] >= n)
{
ok = false;
break;
}
Q.push(G[nod][i]);
inqueue[G[nod][i]] = true;
}
}
}
}
if (ok)
{
for (int i = 2; i <= n; ++i)
{
g << sol[i] << " ";
}
}
else g << "Ciclu negativ!";
f.close();
g.close();
return 0;
}