Pagini recente » Cod sursa (job #1384527) | Cod sursa (job #1187722) | Cod sursa (job #2949368) | Cod sursa (job #1242135) | Cod sursa (job #2892839)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <algorithm>
#include <map>
#include <climits>
std::ifstream f("bellmanford.in");
std::ofstream o("bellmanford.out");
std::vector<int>g[50005];
std::map<std::pair<int, int>, int>costs;
int nodes, edges;
std::vector<int>distances(50005, INT_MAX);
std::vector<int>visited(50005, 0);
bool cycle = false;
void bellman_ford(int start)
{
distances[start] = 0;
for (size_t node = 1; node < nodes; node++)
{
for (auto& edge : costs)
{
if (distances[edge.first.first] + edge.second < distances[edge.first.second])
{
//distances[edge.first.first] + edge.second < distances[edge.first.second]
distances[edge.first.second] = distances[edge.first.first] + edge.second;
}
}
}
for (size_t node = 1; node < nodes; node++)
{
for (auto& edge : costs)
{
if (distances[edge.first.first] + edge.second < distances[edge.first.second])
{
//distances[edge.first.first] + edge.second < distances[edge.first.second]
cycle = true;
return;
}
}
}
}
int main()
{
f >> nodes >> edges;
int i = edges;
while (i--)
{
int start, to, cost;
f >> start >> to >> cost;
g[start].push_back(to);
costs[std::make_pair(start, to)] = cost;
}
bellman_ford(1);
if (cycle==true)
{
o << "Ciclu negativ!";
}
else {
for (size_t i = 2; i <= nodes; i++)
{
o << distances[i] << " ";
}
}
return 0;
}