Pagini recente » Cod sursa (job #663149) | Cod sursa (job #953268) | Cod sursa (job #2779285) | Cod sursa (job #2765492) | Cod sursa (job #2899873)
#include <bits/stdc++.h>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
const int oo = 0x3f3f3f3f;
int n,m;
int d[50005],nr_nod[50005];
bool sel[50005];
vector<pair<int,int>> G[50005];
void Bellman()
{
queue<int> q;
for(int i=1;i<=n;i++)
{
d[i] = oo;
sel[i] = false;
}
d[1] = 0;
sel[1] = true;
nr_nod[1] = 1;
q.push(1);
while(!q.empty())
{
int nod = q.front();
q.pop();
sel[nod] = false;
for(auto it : G[nod])
{
if(d[nod] + it.second < d[it.first])
{
d[it.first] = d[nod] + it.second;
if(!sel[it.first])
{
q.push(it.first);
sel[it.first] = true;
}
nr_nod[it.first] = nr_nod[nod] + 1;
if(nr_nod[it.first] > n)
{
g<<"Ciclu negativ!"<<'\n';
exit(0);
}
}
}
}
for(int i=2;i<=n;i++)
{
g<<d[i]<<' ';
}
g<<'\n';
}
int main()
{
f>>n>>m;
for(int i=1;i<=m;i++)
{
int x,y,c;
f>>x>>y>>c;
G[x].push_back({y,c});
}
Bellman();
return 0;
}