Pagini recente » Cod sursa (job #254667) | Cod sursa (job #518595) | Cod sursa (job #360231) | Cod sursa (job #1692381) | Cod sursa (job #1987709)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int nMax = 50005;
const int mMax = 250005;
const int INF = (1 << 30);
int n, m;
vector<pair<int, int> > vecini[nMax];
int dp[nMax];
int cnt[nMax];
void citire()
{
ifstream in("bellmanford.in");
in >> n >> m;
int x, y, c;
for(int i = 1; i <= m; ++i)
{
in >> x >> y >> c;
vecini[x].push_back(make_pair(y, c));
}
in.close();
}
void rezolvare()
{
ofstream out("bellmanford.out");
queue<int> q;
q.push(1);
cnt[1]++;
dp[1] = 0;
for(int i = 2; i <= n; ++i)
dp[i] = INF;
int nod;
while(q.empty() == false)
{
nod = q.front();
q.pop();
for(auto &v:vecini[nod])
{
if(dp[nod] + v.second < dp[v.first])
{
dp[v.first] = dp[nod] + v.second;
cnt[v.first]++;
if(cnt[v.first] == n)
{
out << "Ciclu negativ!";
return;
}
q.push(v.first);
}
}
}
for(int i = 2; i <= n; ++i)
out << dp[i] << " ";
out.close();
}
int main()
{
citire();
rezolvare();
return 0;
}