Pagini recente » Cod sursa (job #2087923) | Cod sursa (job #1771365) | Cod sursa (job #3233944) | Cod sursa (job #3127425) | Cod sursa (job #2425781)
#include<bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int inf = 1e6;
int N, M, X, Y, cost;
int main()
{
fin>>N>>M;
vector<vector<pair<int,int> > > L(N+1);
for(int i = 1; i <= M; i++)
{
fin>>X>>Y>>cost;
L[X].push_back(make_pair(cost,Y));
}
fin.close();
vector<int> dist(N+1,inf);
vector<int> cnt_in_queue(N+1);
dist[1] = 0;
queue<int> Q;
Q.push(1);
bool negative_cicle = false;
while(!Q.empty() && !negative_cicle)
{
int node = Q.front();
Q.pop();
if(cnt_in_queue[node]>N){
fout<<"Ciclu negativ!";
negative_cicle = true;
return 0;
}
cnt_in_queue[node]++;
for(auto neighbour : L[node])
{
if(dist[node] + neighbour.first < dist[neighbour.second])
{
dist[neighbour.second] = dist[node] + neighbour.first;
Q.push(neighbour.second);
}
}
}
for(int i = 2; i <= N; i++)
fout<<dist[i]<<' ';
fout.close();
return 0;
}