Pagini recente » Cod sursa (job #1324827) | Cod sursa (job #135855) | Cod sursa (job #1954050) | Cod sursa (job #2297860) | Cod sursa (job #3214026)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
const int N = 5e4, INF = 1e8;
int n, m;
int d[N+1], cnt[N+1];
bool in_queue[N+1];
vector < pair<int, int> > g[N+1];
queue <int> q;
bool bellman_ford(int rad)
{
for (int i = 1; i <= n; i++)
d[i] = INF;
d[rad] = 0;
in_queue[rad] = 1;
cnt[rad] = 1;
q.push(rad);
while (!q.empty())
{
int node = q.front();
in_queue[node] = false;
q.pop();
//cout << node << ' ' << d[node] << '\n';
for (vector< pair<int, int> > :: iterator it = g[node].begin(); it != g[node].end(); it++)
{
int vec = it->first;
int cost = it->second;
//cout << vec << ' ' << cost << ' ' << d[vec];
if (d[node] + cost < d[vec])
{
d[vec] = d[node] + cost;
//cout << " " << in_queue[vec];
if (!in_queue[vec])
{
//cout << ' ' << cnt[vec];
if (cnt[vec] > n)
return false;
else
{
in_queue[vec] = true;
cnt[vec]++;
q.push(vec);
}
}
}
//cout << "; ";
}
//cout << "\n";
}
return true;
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= m; i++)
{
int a, b, c;
cin >> a >> b >> c;
g[a].push_back( make_pair(b, c) );
}
bool bun = bellman_ford(1);
if (bun)
{
for (int i = 2; i <= n; i++)
cout << d[i] << ' ';
}
else
cout << "Ciclu negativ!";
return 0;
}