Pagini recente » Cod sursa (job #627120) | Rating Manuel Esanu (Estiarte) | Cod sursa (job #954601) | Cod sursa (job #401388) | Cod sursa (job #3272359)
#include <bits/stdc++.h>
namespace BellmanFord{
using namespace std;
#ifdef fakeFILES
std::ifstream fin("input.in");
std::ofstream fout("input.out");
#else
std::ifstream fin("bellmanford.in");
std::ofstream fout("bellmanford.out");
#endif
int const N = 50005, INF = 1e9;
int n;
std::vector< pair<int,int> > g[N];
bool bellman(int start = 1){
int dist[N],dad[N];
fill(dist, dist+N, INF);
fill(dad,dad+N,0);
dad[start] = start;
dist[start] = 0;
for(int i = 0 ; i <= n ; i++){
/// relax all edges:
for(int node = 1; node <= n ; node ++){
for(auto edge:g[node]){
int v = edge.first; /// neighbour
int cost = edge.second;
if(dist[node] + cost < dist[v]){
dist[v] = dist[node] + cost;
dad[v] = node;
}
}
}
}
for(int node = 1; node <= n ; node ++){
for(auto edge:g[node]){
int v = edge.first; /// neighbour
int cost = edge.second;
if(dist[node] + cost < dist[v])
return false;
}
}
for(int node = 1; node <= n ; node ++){
if(node != start)
fout << dist[node] << ' ';
}
return true;
}
void run(){
int m;
fin >> n >> m;
while(m--){
int x,y,c;
fin >> x >> y >> c;
g[x].emplace_back(y,c);
}
if(!bellman(1))
fout << "Ciclu negativ!";
}
}
/*******************
MOMENTAN LIPSESC:
- muchii / noduri critice.
- componente tare conexe.
- APM kruskal / prim.
- FLUX de cost max;
- euler normal la cap.
- teorema celor 6/5 culori.
- dist levenstein (usor).
*******************/
int main()
{
BellmanFord::run();
}