Pagini recente » Cod sursa (job #1658188) | Cod sursa (job #1207561) | Cod sursa (job #2550188) | Cod sursa (job #238182) | Cod sursa (job #1779014)
#include <stdio.h>
#include <vector>
#include <queue>
#include <stdlib.h>
#define inf 10000000
using namespace std;
int n,m,i,f[50001],d[50001],x,y,c;
bool o[50001];
vector<pair<int,int> >G[50005];
queue<int> Q;
void bellmanford()
{
int x,i,y;
Q.push(1);
for (i=2;i<=n;i++) d[i]=inf;
while (!Q.empty())
{
x=Q.front();
Q.pop();
o[x]=0;
for (i=0;i<G[x].size();i++)
{
y=G[x][i].first;
if (d[y]>d[x]+G[x][i].second)
{
d[y]=d[x]+G[x][i].second;
if (!o[y])
{
o[y]=1;
Q.push(y);
f[y]++;
if (f[y]==n+1)
{
printf("Ciclu negativ!");
exit(0);
}
}
}
}
}
}
int main()
{
freopen ("bellmanford.in","r",stdin);
freopen ("bellmanford.out","w",stdout);
scanf("%i%i",&n,&m);
for (i=1;i<=m;i++)
{
scanf("%i%i%i",&x,&y,&c);
G[x].push_back(make_pair(y,c));
}
bellmanford();
for (i=2;i<=n;i++)
printf("%i ",d[i]);
fclose(stdin);
fclose(stdout);
return 0;
}