Pagini recente » Cod sursa (job #671796) | Cod sursa (job #828190) | Cod sursa (job #1260618) | Cod sursa (job #167937) | Cod sursa (job #3186007)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int INF = 1e9;
int n, m, d[50001], v[50001], cnt[50001];
vector<pair<int, int>> g[50001];
queue<int> q;
int main(){
fin >> n >> m;
for(int i = 1; i <= m; i++){
int x, y, c;
fin >> x >> y >> c;
g[x].push_back({y, c});
}
for(int i = 1; i <= n; i++) d[i] = INF;
d[1] = 0;
q.push(1);
while (!q.empty())
{
int k = q.front();
q.pop();
v[k] = 0;
for(auto p : g[k]){
int y = p.first, c = p.second;
if(d[k] + c < d[y]){
d[y] = d[k] + c;
if(v[y] == 0){
v[k] = 1;
q.push(y);
cnt[y]++;
if(cnt[y] > n){
fout << "Ciclu negativ!";
fin.close();
fout.close();
return 0;
}
}
}
}
}
for(int i = 2; i <= n; i++) fout << d[i] << ' ';
fin.close();
fout.close();
return 0;
}