Pagini recente » Cod sursa (job #793147) | Cod sursa (job #1582819) | Cod sursa (job #3162557) | Cod sursa (job #689197) | Cod sursa (job #1364212)
#include<cstdio>
#include<string>
#include<deque>
#include<bitset>
#include<vector>
using namespace std;
#ifdef HOME
const string inputFile = "input.txt";
const string outputFile = "output.txt";
#else
const string problemName = "bellmanford";
const string inputFile = problemName + ".in";
const string outputFile = problemName + ".out";
#endif
typedef pair<int, int> PII;
const int INF = (1 << 30);
const int NMAX = 50000 + 5;
int N, M;
vector<PII> V[NMAX];
int D[NMAX];
int nr[NMAX];
bitset<NMAX> viz;
deque<int> Q;
int bfs(int x) {
int i, y, z;
for(i = 1; i <= N; i++)
D[i] = INF;
D[x] = 0;
Q.push_back(x);
viz[x] = 1;
while(!Q.empty()) {
x = Q.front();
Q.pop_front();
viz[x] = 0;
nr[x]++;
if(nr[x] >= N)
return 0;
for(auto p : V[x]) {
y = p.first;
z = p.second;
if(D[x] + z < D[y]) {
D[y] = D[x] + z;
if(!viz[y]) {
Q.push_back(y);
viz[y] = 1;
}
}
}
}
return 1;
}
int main() {
int i, x, y, z;
freopen(inputFile.c_str(), "r", stdin);
freopen(outputFile.c_str(), "w", stdout);
scanf("%d%d", &N, &M);
while(M--) {
scanf("%d%d%d", &x, &y, &z);
V[x].push_back(make_pair(y, z));
}
if(bfs(1))
for(i = 2; i <= N; i++)
printf("%d ", D[i]);
else
printf("Ciclu negativ!");
return 0;
}