Pagini recente » Cod sursa (job #1098622) | Cod sursa (job #30020) | Cod sursa (job #1455193) | Cod sursa (job #2750611) | Cod sursa (job #2498394)
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
using namespace std;
#define MAX_N 50010
#define INF 0x7FFFFFFF
/**
`-.`'.-'
`-. .-'.
`-. -./\.- .-'
-. /_|\ .-
`-. `/____\' .-'.
`-. -./.-""-.\.- '
`-. /< (()) >\ .-'
- .`/__`-..-'__\' .-
,...`-./___|____|___\.-'.,.
,-' ,` . . ', `-,
,-' ________________ `-,
,'/____|_____|_____\
/ /__|_____|_____|___\
/ /|_____|_____|_____|_\
' /____|_____|_____|_____\
.' /__|_____|_____|_____|___\
,' /|_____|_____|_____|_____|_\
,,---''--...___...--'''--.. /../____|_____|_____|_____|_____\ ..--```--...___...--``---,,
'../__|_____|_____|_____|_____|___\
\ ) '.:/|_____|_____|_____|_____|_____|_\ ( /
)\ / ) ,':./____|_____|_____|_____|_____|_____\ ( \ /(
/ / ( ( /:../__|_____|_____|_____|_____|_____|___\ ) ) \ \
| | \ \ /.../|_____|_____|_____|_____|_____|_____|_\ / / | |
.-.\ \ \ \ '..:/____|_____|_____|_____|_____|_____|_____\ / / / /.-.
(= )\ `._.' | \:./ _ _ ___ ____ ____ _ _ _ _ _ _ _ __\ | `._.' /( =)
\ (_) ) \/ \ ( (_) /
\ `----' """""""""""""""""""""""""""""""""""""""""""""" `----' /
\ ____\__ __/____ /
\ (=\ \ / /-) /
\_)_\ \ / /_(_/
\ \ / /
) ) _ _ ( (
( (,-' `-..__ __..-' `-,) )
\_.-'' ``-..____ ____..-'' ``-._/
`-._ ``--...____...--'' _.-'
`-.._ _..-'
`-..__ FORTIS FORTUNA ADIUVAT __..-'
``-..____ ____..-''
``--...____...--''
*/
std::ifstream f("bellmanford.in");
std::ofstream t("bellmanford.out");
int main() {
int n, m;
bool negative = false;
vector <pair <int, int> > graph[MAX_N];
vector <int> distance(MAX_N);
auto bellman_ford = [&distance, &graph, &n, &negative]
(const unsigned& start) mutable {
bitset<MAX_N> in_queue;
std::vector<unsigned> relaxations(1 + n, 0);
std::queue<unsigned> q;
for (auto& iterator : distance) {
iterator = INF;
}
q.push(start);
in_queue[start] = true;
distance[start] = 0;
while (!q.empty()) {
auto current = q.front();
q.pop();
in_queue[current] = false;
for (auto iterator : graph[current]) {
if (distance[current] + iterator.second < distance[iterator.first]) {
if (++relaxations[iterator.first] == n) {
negative = true;
return;
}
else {
if (!in_queue[iterator.first])
q.push(iterator.first);
distance[iterator.first] = distance[current] + iterator.second;
}
}
}
}
};
f >> n >> m;
for (int x, y, c, i = 0; i < m; ++i) {
f >> x >> y >> c;
graph[x].push_back({ y, c });
}
bellman_ford(1);
if (!negative)
for (int i = 2; i <= n; ++i)
t << distance[i] << " ";
else
t << "Ciclu negativ!";
return 0;
}