Pagini recente » Cod sursa (job #1254574) | Cod sursa (job #1843814) | Cod sursa (job #1593562) | Cod sursa (job #2779766) | Cod sursa (job #935110)
Cod sursa(job #935110)
#include <iostream>
#include<vector>
#include<queue>
#include<cstdio>
#define maxn 50073
#define infinit 1<<30
using namespace std;
int cost[maxn],n,m,treceri[maxn];
bool viz[maxn];
typedef struct
{
int nod;
int cost;
}pereche;
vector <pereche> graf[maxn];
void inserare(int nod1,int nod2,int cost)
{
pereche p;
p.nod=nod2;
p.cost=cost;
graf[nod1].push_back(p);
}
int main()
{
int x,y,c;
freopen("bellmanford.in","r",stdin);
freopen("bellmanford.out","w",stdout);
cin>>n>>m;
for (int i=1;i<=m;i++)
{
cin>>x>>y>>c;
inserare(x,y,c);
}
fill(cost,cost+n+1,infinit);
fill(treceri,treceri+n+1,false);
queue <int> coada;
coada.push(1);
treceri[1]++;
cost[1]=0;
while (!coada.empty())
{
int nod=coada.front();
coada.pop();
viz[nod]=false;
for (unsigned int i=0;i<graf[nod].size();i++)
{
int next = graf[nod][i].nod;
if (cost[next]>graf[nod][i].cost+cost[nod])
{
cost[next]=graf[nod][i].cost+cost[nod];
if (!viz[next])
{
if (treceri[next]==n)
{
printf("Ciclu negativ!");
return 0;
}
else
{
coada.push(next);
viz[next]=true;
treceri[next]++;
}
}
}
}
}
for (int i=2;i<=n;i++)
cout<<cost[i]<<" ";
return 0;
}