Pagini recente » Cod sursa (job #1292212) | Cod sursa (job #83631) | Cod sursa (job #1408897) | Cod sursa (job #2070040) | Cod sursa (job #2693158)
#include <iostream>
#include <fstream>
#include <vector>
#include <deque>
using namespace std;
int d[50005], ex[50005];
vector <pair<int, int>> graph[50005];
deque <int> q;
int main()
{
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n, m, x, y, z;
f>>n>>m;
for(int i=1; i<=m; i++)
{
f>>x>>y>>z;
graph[x].push_back(make_pair(y,z));
}
for(int i=2; i<=n; i++)
d[i] = 10001;
d[1] = 0;
q.push_back(1);
while(!q.empty())
{
int k = q.front();
q.pop_front();
ex[k] = 0;
for(auto j : graph[k])
{
if(d[k] + j.second < d[j.first])
{
d[j.first] = d[k] + j.second;
if(ex[j.first] == 0)
{
ex[j.first] = 1;
q.push_back(j.first);
}
}
}
}
for(int i=1; i<=n; i++)
for(auto j : graph[i])
if(d[i] + j.second < d[j.first])
{
cout<<"Ciclu negativ!";
return 0;
}
for(int i=2; i<=n; i++)
cout<<d[i]<<" ";
return 0;
}