Pagini recente » Cod sursa (job #2156566) | Cod sursa (job #1253653) | Cod sursa (job #1026413) | Cod sursa (job #1291046) | Cod sursa (job #2666712)
#include <bits/stdc++.h>
#define NMAX 50005
#define INF 2e9
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n, m, x, y, pas;
int path[NMAX], visited[NMAX];
vector < pair< int, int > > nod[NMAX];
queue < int > q;
void read(){
f>>n>>m;
for(int i = 1; i <= m; ++i){
f>>x>>y>>pas;
nod[x].push_back(make_pair(y, pas));
}
for(int i = 2; i <= n; ++i)
path[i] = INF;
f.close();
}
void print(){
for(int i = 2; i <= n; ++i)
g<<path[i]<<' ';
}
int main()
{
read();
int next_node;
for(int i = 2; i <= n; ++i)
path[i] = INF;
path[1] = 0;
q.push(1);
while(!q.empty()){
next_node = q.front();
visited[next_node]++;
q.pop();
if(visited[next_node] > n){
g<<"Ciclu negativ!";
return 0;
}
for(auto it:nod[next_node])
if(path[it.first] > path[next_node] + it.second){
path[it.first] = path[next_node] + it.second;
q.push(it.first);
}
}
print();
g.close();
return 0;
}