Pagini recente » Solutia problemei shoturi | Cod sursa (job #2458202) | Cod sursa (job #554242) | Cod sursa (job #1658041) | Cod sursa (job #2979992)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
bool a[50010], gasit;
int n, m, dist[50010];
vector <pair <int, int>> v[50010];
queue <int> q;
void parc(int x)
{
dist[x]=0;
a[x]=1;
q.push(x);
while(!q.empty() && gasit==0)
{
int nod=q.front();
q.pop();
a[nod]=0;
for(int i=0; i<v[nod].size(); i++)
{
int vecin=v[nod][i].first;
int cost=v[nod][i].second;
if(dist[nod]+cost<0 && vecin==1)
{
gasit=1;
g<<"Ciclu negativ!";
}
if(dist[nod]+cost<dist[vecin])
{
dist[vecin]=dist[nod]+cost;
if(!a[vecin])
{
q.push(vecin);
a[vecin]=1;
}
}
}
}
}
int main()
{
f>>n>>m;
for(int i=1; i<=m; i++)
{
int x, y, c;
f>>x>>y>>c;
v[x].push_back(make_pair(y, c));
}
for(int i=1; i<=n; i++)
dist[i]=2e9;
parc(1);
for(int i=2; i<=n && gasit==0; i++)
g<<dist[i]<<" ";
return 0;
}