Pagini recente » Cod sursa (job #441932) | Cod sursa (job #1370988) | Cod sursa (job #624426) | Cod sursa (job #2833003) | Cod sursa (job #1845577)
#include <fstream>
#include <vector>
#define nmax 50001
#define INF 1<<30
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n,m,cost[nmax];
bool viz[nmax],ok=true;
vector < pair < int, int > > leg[nmax];
inline void read()
{
int i,a,b,c;
fin>>n>>m;
for(i=2; i<=n; i++)
cost[i]=INF;
for(i=1; i<=m; i++)
{
fin>>a>>b>>c;
leg[a].push_back(make_pair(b,c));
}
fin.close();
}
inline void bellford()
{
int i,rd,j;
for(rd=1; rd<n; rd++)
{
for(i=1; i<=n; i++)
{
if(viz[i]==false)
{
viz[i]=true;
for(j=0; j<leg[i].size(); j++)
{
if(cost[leg[i][j].first]>cost[i]+leg[i][j].second)
{
cost[leg[i][j].first]=cost[i]+leg[i][j].second;
viz[leg[i][j].first]=false;
}
}
}
}
}
for(i=1; i<=n; i++)
{
if(viz[i]==false)
{
for(j=0; j<leg[i].size(); j++)
{
if(cost[leg[i][j].first]>cost[i]+leg[i][j].second)
{
ok=false;
break;
}
}
}
}
}
inline void write()
{
if(ok==false)
fout<<"Ciclu negativ!";
else
{
for(int i=2;i<=n;i++)
fout<<cost[i]<<' ';
}
fout.close();
}
int main()
{
read();
bellford();
write();
return 0;
}