Pagini recente » Cod sursa (job #952984) | Cod sursa (job #473921) | Cod sursa (job #1215025) | Cod sursa (job #1883044) | Cod sursa (job #1341870)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <algorithm>
#include <string.h>
#define inf 0x3f3f3f3f
#define max 50001
using namespace std;
int n,m;
int nmax[max];
int d[max];
vector<pair<int,int> > g[max];
queue<int> q;
bool viz[max];
void citire()
{
scanf("%d %d",&n,&m);
int x,y,c;
for(int i=1;i<=m;i++)
{
scanf("%d %d %d",&x,&y,&c);
g[x].push_back(make_pair(y,c));
}
}
void bellman()
{
q.push(1);
memset(d, inf, sizeof(d));
d[1]=0;
while(!q.empty())
{
int top=q.front();
q.pop();
viz[top]=false;
for(int i=0;i<g[top].size();i++)
if(d[g[top][i].first]>d[top]+g[top][i].second)
{
if(++nmax[top]>=n)
{ printf("Ciclu negativ!");
exit(0);
}
if(!viz[g[top][i].first])
q.push(g[top][i].first);
viz[g[top][i].first]=true;
d[g[top][i].first]=d[top]+g[top][i].second;
}
}
}
void afisare()
{
int i;
for (i=2; i<=n; i++)
printf("%d ", d[i]);
}
int main()
{
freopen("bellmanford.in", "r", stdin);
//freopen("bellmanford.out", "w", stdout);
citire();
bellman();
afisare();
return 0;
}