Pagini recente » Cod sursa (job #2120725) | Cod sursa (job #205444) | Cod sursa (job #1569769) | Cod sursa (job #2225148) | Cod sursa (job #1645995)
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <bitset>
#define nmax 50006
#define inf 0x7fffffff;
using namespace std;
int n,m1;
int cnt[nmax],d[nmax];
vector< pair<int,int> > m[nmax];
queue<int> q;
queue<int>c;
bitset<nmax> inq;
inline bool bellf()
{
int nod,ciclu;
vector< pair<int,int> >::iterator it;
for(int i=1;i<=n;i++) d[i]=inf;
inq.reset();
q.push(1); inq[1]=1; d[1]=0;
ciclu=0;
while(!q.empty())
{
nod=q.front(); q.pop(); inq[nod]=0;
for(it=m[nod].begin();it!=m[nod].end();it++)
if(d[ it->first ]> d[nod]+ it->second)
{
d[it->first]=d[nod]+it->second;
if(!inq[it->first])
if(cnt[it->first]>n) ciclu=1;
else
{
q.push(it->first);
inq[it->first]=1;
cnt[it->first]++;
}
}
}
return ciclu;
}
int main()
{
int i,n1,n2,cost;
freopen("bellmanford.in","r",stdin);
freopen("bellmanford.out","w",stdout);
scanf("%d%d",&n,&m1);
for(;m1;m1--)
{
scanf("%d%d%d",&n1,&n2,&cost);
m[n1].push_back( make_pair(n2,cost) );
}
if(!bellf())
for(i=2;i<=n;i++) printf("%d ",d[i]);
else printf("Ciclu negativ!\n");
fclose(stdin);
fclose(stdout);
return 0;
}