Pagini recente » Cod sursa (job #935631) | Cod sursa (job #433917) | Cod sursa (job #2123698) | Cod sursa (job #3161691) | Cod sursa (job #3295136)
#include <bits/stdc++.h>
using namespace std;
vector <pair<int,int>> graph[50005];
int distances[50005];
int noOfNodes[50005];
bool IsInQueue[50005];
void bellman(int source, int n)
{
for(int i=1; i<=n; i++)
{
distances[i]=1e9;
}
queue <int> q;
distances[source]=0;
noOfNodes[source]=1;
q.push(source);
IsInQueue[source]=true;
while(!q.empty())
{
int node = q.front();
q.pop();
IsInQueue[node]=false;
if(noOfNodes[node] > n)
{
cout<<"Ciclu negativ!";
exit(0);
}
for(auto x : graph[node])
{
if(distances[x.first] > distances[node] + x.second)
{
distances[x.first] = distances[node] + x.second;
noOfNodes[x.first] = noOfNodes[node] + 1;
if(!IsInQueue[x.first])
{
q.push(x.first);
}
}
}
}
}
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int main()
{
int n, m;
fin>>n>>m;
for(int i=0; i<m; i++)
{
int u, v, w;
fin>>u>>v>>w;
graph[u].push_back({v,w});
}
int source = 1;
bellman(source,n);
for(int i=2; i<=n; i++)
{
fout<<distances[i]<<" ";
}
return 0;
}