Pagini recente » Cod sursa (job #1069133) | Cod sursa (job #2876589) | Cod sursa (job #2648625) | Cod sursa (job #1546433) | Cod sursa (job #2888430)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int CMAX = 5e4+15;
const int oo = INT_MAX;
int n , m , x , y , c;
int D[CMAX];
int viz[CMAX];
vector < pair < int , int > > graf[CMAX];
queue < int > Q;
void citire()
{
fin >> n >> m;
for(int i=1;i<=m;i++)
{
fin >> x >> y >> c;
graf[x].push_back({y,c});
//cout << x << " " << y << " " << c << '\n';
}
/*
for(int i=1;i<=n;i++)
{
cout << i << ": ";
for(int j=0;j<graf[i].size();j++)
{
cout << graf[i][j].first << ", " << graf[i][j].second << " |";
}
cout << '\n';
}
*/
}
bool bellmanford(int start){
for(int i=1;i<=n;i++){
viz[i] = 0;
D[i] = oo;
}
D[start] = 0;
Q.push(start);
while(!Q.empty())
{
int nod_curent = Q.front();
Q.pop();
viz[nod_curent]++;
//cout << "nod: " << nod_curent << '\n';
if(viz[nod_curent]>=n)
return false;
//cout << "vecini: ";
for(int i=0;i<graf[nod_curent].size();i++)
{
int vecin = graf[nod_curent][i].first;
int cost = graf[nod_curent][i].second;
if(D[nod_curent]+cost<D[vecin]){
D[vecin] = D[nod_curent] + cost;
Q.push(vecin);
}
}
}
return true;
}
int main()
{
citire();
if(bellmanford(1)==false)
{
fout << "Ciclu negativ!";
}
else
{
for(int i=2;i<=n;i++)
fout << D[i] << " ";
}
return 0;
}