Pagini recente » infoarena - comunitate informatica, concursuri de programare | Cod sursa (job #2719765) | Cod sursa (job #1281827) | Cod sursa (job #3193307) | Cod sursa (job #3207412)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
struct muchie
{
int y,c;
};
const long long INF=100000005;
const int NMAX=50005;
vector<muchie> G[NMAX];
int dist[NMAX],viz[NMAX];
int n,m;
void read()
{
f >> n >> m;
for(int i=1;i<=m;i++)
{
int x,y,c;
f >> x >> y >> c;
G[x].push_back({y,c});
}
}
void init()
{
for(int i=1;i<=n;i++)
{
dist[i]=INF;
}
dist[1]=0;
}
queue<int> q;
void bellmanford(int nod)
{
q.push(nod);
while(!q.empty())
{
int nodc=q.front();
q.pop();
for(auto vec:G[nodc])
{
if(dist[vec.y]>dist[nodc]+vec.c)
{
dist[vec.y]=dist[nodc]+vec.c;
q.push(vec.y);
}
}
}
}
int main()
{
read();
init();
bellmanford(1);
for(int i=1;i<=n;i++)
{
for(auto vec:G[i])
{
if(dist[vec.y]>dist[i]+vec.c)
{
g << "Ciclu negativ!";
}
}
}
for(int i=2;i<=n;i++)
{
g << dist[i] << " ";
}
return 0;
}