Pagini recente » Cod sursa (job #2101545) | Cod sursa (job #1784856) | Cod sursa (job #892280) | Cod sursa (job #1221373) | Cod sursa (job #3214971)
#include <bits/stdc++.h>
#pragma optimize GCC ("Ofast")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
///#include <tryhardmode>
///#include <GODMODE::ON>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
const int NMAX=5e4+5;
const int INF=2e9;
vector<pair<int,int>>v[NMAX];
int dist[NMAX];
bool viz[NMAX];
int freq[NMAX];
bool flag;
int n;
void bellman(int p)
{
queue<int>q;
viz[p]=true;
dist[p]=0;
q.push(p);
while(!q.empty())
{
int p=q.front();
q.pop();
viz[p]=false;
for(auto i:v[p])
{
if(dist[i.first]>dist[p]+i.second)
{
dist[i.first]=dist[p]+i.second;
freq[i.first]++;
if(freq[i.first]>n)
{
fout<<"Ciclu negativ\n";
exit(0);
}
if(!viz[i.first])
{
viz[i.first]=true;
q.push(i.first);
}
}
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
fin.tie(NULL);
fout.tie(NULL);
int m,i,j;
fin>>n>>m;
for(i=1;i<=m;i++)
{
int x,y,c;
fin>>x>>y>>c;
v[x].push_back(make_pair(y,c));
}
for(i=1;i<=n;i++)
dist[i]=INF;
bellman(1);
for(i=2;i<=n;i++)
if(dist[i]==INF)
fout<<0<<" ";
else
fout<<dist[i]<<" ";
return 0;
}