Pagini recente » Cod sursa (job #512645) | Cod sursa (job #1333324) | Cod sursa (job #1428313) | Cod sursa (job #357410) | Cod sursa (job #1365067)
#include <cstdio>
#include <vector>
#include <bitset>
#include <algorithm>
#include <queue>
#define Nmax 50005
#define INF 0x3f3f3f3f
using namespace std;
vector<vector<pair<int,int> > > G;
bitset<Nmax> inQ;
queue<int> Q;
vector<int> nrq,DP;
int N,M;
void Read()
{
scanf("%d%d",&N,&M);
G.resize(N+1);
DP.resize(N+1);
nrq.resize(N+1);
int a,b,c;
for(int i = 1; i <= M; ++i)
{
scanf("%d%d%d",&a,&b,&c);
G[a].push_back(make_pair(c,b));
}
}
void Bellman_Ford(int k)
{
DP.assign(N+1,INF);
DP[k] = 0;
Q.push(k);
while(!Q.empty())
{
k = Q.front(); Q.pop(); inQ[k] = 0;
for(vector<pair<int,int> >::iterator it = G[k].begin(); it != G[k].end(); ++it)
if(DP[it->second] > DP[k] + it->first)
{
DP[it->second] = DP[k] + it->first;
if(inQ[it->second])
continue;
inQ[it->second] = 1;
Q.push(it->second);
++nrq[it->second];
if(nrq[it->second] >= N)
{
printf("Ciclu negativ!\n");
return;
}
}
}
for(int i = 2; i <= N; ++i)
printf("%d ", DP[i]);
}
int main()
{
freopen("bellmanford.in","r",stdin);
freopen("bellmanford.out","w",stdout);
Read();
Bellman_Ford(1);
return 0;
}