Pagini recente » Cod sursa (job #1133414) | Monitorul de evaluare | Cod sursa (job #1176375) | Cod sursa (job #1878186) | Cod sursa (job #2163806)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
using PII = pair<int,int>;
vector <PII> G[50001];
int d[50001],p[50001],nr[50001];
int n,m;
const int Inf=0x3f3f3f3f;
bool v[50001];
int main()
{
fin>>n>>m;
while(m--)
{
int x,y,cost;
fin>>x>>y>>cost;
G[x].push_back({y,cost});
}
for(int i=0;i<=n;++i)
{
d[i]=Inf; p[i]=0; v[i]=false;
}
v[1]=true;
d[1]=0;
queue <int> Q;
Q.push(1);
while(!Q.empty())
{
int nod=Q.front();
v[nod]=false;
vector <PII>::iterator it;
for(it=G[nod].begin();it!=G[nod].end();++it)
if(d[nod]+it->second<d[it->first])
{
d[it->first]=d[nod]+it->second;
if(!v[it->first])
{
if(nr[it->first]>n)
{
fout<<"Ciclu negativ!\n";
return 0;
}
Q.push(it->first);
v[it->first]=true;
++nr[it->first];
}
}
Q.pop();
}
for(int i=2;i<=n;++i)
fout<<d[i]<<" ";
return 0;
}