Pagini recente » Cod sursa (job #2639697) | Cod sursa (job #2248284) | Cod sursa (job #1222669) | Cod sursa (job #3288955) | Cod sursa (job #3200953)
#include <fstream>
#include <vector>
#include <set>
using namespace std;
ifstream cin ("bellmanford.in");
ofstream cout ("bellmanford.out");
int u[50005];
int n,m;
vector < pair<int,int> > g[50005];
int d[50005];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for(int i=1;i<=m;i++)
{
int x,y,c;
cin >> x >> y >> c;
g[x].push_back({y,c});
}
for(int i=1;i<=n;i++)
d[i] = 1e9;
d[1] = 0;
set < pair<int,int> > pq;
pq.insert({0,1});
while(!pq.empty())
{
pair<int,int> vf = *pq.begin();
pq.erase(vf);
int dist = vf.first;
int nod = vf.second;
if(d[nod]!=dist)
continue;
for(auto much:g[nod])
{
int urm = much.first;
int c = much.second;
if(d[urm] > dist + c)
{
d[urm] = dist + c;
pq.insert({d[urm],urm});
u[urm]++;
if(u[urm] > n)
{
cout << "Ciclu negativ!";
return 0;
}
}
}
}
for(int i=2;i<=n;i++)
cout << d[i] << ' ';
return 0;
}