Pagini recente » Cod sursa (job #2031524) | Cod sursa (job #2655248) | Cod sursa (job #1012667) | Cod sursa (job #1772120) | Cod sursa (job #1108455)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#define maxn 50001
using namespace std;
int n,m;
vector < pair<int,int> > Graf[maxn];
int best[maxn];
bool viz[maxn];
int ct[maxn];
struct cmp
{
inline bool operator () (const int &A, const int &B)
{
return best[A] > best[B];
}
};
priority_queue <int ,vector <int>, cmp> Q;
int Bellmanford()
{
memset(best,0x3f,sizeof(best));
vector < pair<int,int> > :: iterator it;
best[1]=0;
Q.push(1);
while(!Q.empty())
{
int now;
now=Q.top();
Q.pop();
viz[now]=0;
for(it=Graf[now].begin();it!=Graf[now].end();it++)
if(best[now]+it->second < best[it->first] )
{
best[it->first]=best[now]+it->second;
if(!viz[it->first])
{
viz[it->first]=1;
Q.push(it->first);
++ct[it->first];
if(ct[it->first]>=n)
{
printf("Ciclu negativ!");
exit(0);
}
}
}
}
}
int main()
{
freopen ("bellmanford.in", "r", stdin);
freopen ("bellmanford.out", "w", stdout);
cin>>n>>m;
int x,y,z;
while(m--)
{
scanf("%d%d%d",&x,&y,&z);
//cin>>x>>y>>z;
Graf[x].push_back(make_pair(y,z));
}
Bellmanford();
for(int i=2;i<=n;i++)
//cout<<best[i]<<" ";
printf("%d ",best[i]);
return 0;
}