Pagini recente » Cod sursa (job #85061) | Cod sursa (job #1458179) | Cod sursa (job #2192737) | Cod sursa (job #1102161) | Cod sursa (job #3268337)
#include<fstream>
#include<queue>
#include<vector>
#include<bitset>
#define INF 1000000000
std::ifstream fin("bellmanford.in");
std::ofstream fout("bellmanford.out");
const int NMAX=50005;
std::vector<std::pair<int, int>>G[NMAX];
std::vector<int>dist(NMAX, INF);
std::vector<int>cnt(NMAX);
std::bitset<NMAX>f;
int n, m;
void read()
{
fin>>n>>m;
for(int i=0; i<m; ++i)
{
int from, to, cost;
fin>>from>>to>>cost;
G[from].emplace_back(to, cost);
}
}
void bellman_ford()
{
dist[1]=0;
f[1]=true;
std::queue<int>q;
q.push(1);
while(!q.empty())
{
int node=q.front();
q.pop();
//f[node]=false;
if(cnt[node]==n)
{
fout<<"Ciclu negativ!";
std::exit(0);
}
for(auto it:G[node])
{
int y=it.first, cost=it.second;
if(dist[y]>dist[node]+cost)
{
dist[y]=dist[node]+cost;
++cnt[y];
q.push(y);
}
}
}
for(int i=2; i<=n; ++i)
fout<<dist[i]<<' ';
}
int main()
{
read();
bellman_ford();
return 0;
}