Pagini recente » Cod sursa (job #698217) | Cod sursa (job #2552206) | Cod sursa (job #785704) | Cod sursa (job #2615365) | Cod sursa (job #1171859)
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int INF = 0x3f3f3f3f;
int N, M;
vector<pair<int, int> > V[50002];
int D[50002], times[50002];
queue<int> Q;
bool inqueue[50002];
int main()
{
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
fin >> N >> M;
for (int i = 1, nod1, nod2, cost; i <= M; ++i)
{
fin >> nod1 >> nod2 >> cost;
V[nod1].push_back(make_pair(nod2, cost));
}
for (int i = 1; i <= N; ++i)
D[i] = INF;
D[1] = 0;
Q.push(1);
inqueue[1] = true;
bool ok = true;
while (!Q.empty() && ok)
{
int now = Q.front();
inqueue[now] = false;
for (vector<pair<int, int> >::iterator it = V[now].begin(); it != V[now].end(); ++it)
if (D[now] + it->second < D[it->first])
{
D[it->first] = D[now] + it->second;
++times[it->first];
if (times[it->first] >= N)
{
ok = false;
break;
}
if (!inqueue[it->first])
{
Q.push(it->first);
inqueue[it->first] = true;
}
}
Q.pop();
}
if (!ok) fout << "Ciclu negativ!\n";
else
{
for (int i = 2; i <= N; ++i)
fout << D[i] << ' ';
fout << '\n';
}
fin.close();
fout.close();
}