Pagini recente » Cod sursa (job #2403814) | Cod sursa (job #2889819)
#include <iostream>
#include <vector>
#include <fstream>
#include <string.h>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
#define INF 10000000
int n, m, x, y, c;
int dist[INF];
int marked[INF];
vector < pair <int, int> > edges[INF];
queue <int> Q;
void input()
{
fin >> n >> m;
for(int i = 1; i <= m; i++)
{
fin >> x >> y >> c;
edges[x].push_back({y,c});
}
}
bool bellmanford(int start)
{
for(int i = 1; i <= n; i++)
dist[i] = INF;
memset(marked, 0, sizeof(marked));
dist[start] = 0;
Q.push(start);
while(!Q.empty())
{
int current_node = Q.front();
Q.pop();
marked[current_node]++;
if(marked[current_node] >= n)
return false;
for(int i = 0; i < edges[current_node].size(); i++)
{
int next_node = edges[current_node][i].first;
int cost = edges[current_node][i].second;
if(dist[current_node] + cost < dist[next_node])
{
dist[next_node] = dist[current_node] + cost;
Q.push(next_node);
}
}
}
return true;
}
int main()
{
input();
if(bellmanford(1) == false)
{
fout << "Ciclu negativ!";
}
else
for(int i = 2; i <= n; i++)
fout << dist[i] << " ";
return 0;
}