Pagini recente » Cod sursa (job #258698) | Cod sursa (job #1228355) | Cod sursa (job #2139460) | Cod sursa (job #446185) | Cod sursa (job #1493502)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <utility>
#include <algorithm>
#define MaxN 50005
#define Inf 123456789
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int N, M, x, y, c;
vector<pair<int, int> > G[MaxN];
int main()
{
fin >> N >> M;
for (int i = 1; i <= M; ++i) {
fin >> x >> y >> c;
G[x].push_back(make_pair(y, c));
}
queue<int> q;
bitset<MaxN> inQueue(false);
vector<int> dist(N + 1, Inf), countInQueue(N + 1, 0);
bool negativeCycle = false;
dist[1] = 0;
q.push(1);
while (!q.empty() && !negativeCycle) {
int node = q.front();
q.pop();
inQueue[node] = false;
vector<pair<int, int> >::iterator it;
for (it = G[node].begin(); it != G[node].end(); ++it) {
if (dist[node] + it->second < dist[it->first]) {
dist[it->first] = dist[node] + it->second;
if (!inQueue[it->first]) {
if (countInQueue[it->first] > N) {
negativeCycle = true;
} else {
q.push(it->first);
inQueue[it->first] = true;
countInQueue[it->first]++;
}
}
}
}
}
if (negativeCycle) {
fout << "Ciclu negativ!\n";
} else {
for (int i = 2; i <= N; ++i)
fout << dist[i] << ' ';
fout << '\n';
}
return 0;
}