Pagini recente » Diferente pentru teorema-chineza-a-resturilor intre reviziile 80 si 89 | Cod sursa (job #1006045) | Istoria paginii runda/sim02 | Statistici Moldovan Andrei (Dei_Andrei_rg) | Cod sursa (job #979740)
Cod sursa(job #979740)
# include <cstdlib>
# include <cstring>
# include <iostream>
# include <fstream>
# include <vector>
# include <queue>
using namespace std;
# define INF 0x3f3f3f3f
# define MAXN 50010
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n, m;
vector<pair<int, int> > G[MAXN];
int dist[MAXN];
queue<int> coada;
void bfs(int nod)
{
memset(dist, 0x3f, sizeof(dist));
dist[nod] = 0;
coada.push(nod);
while (!coada.empty() && dist[nod] >= 0) {
int nd = coada.front();
coada.pop();
for (int i = 0; i < G[nd].size(); i++) {
if (dist[G[nd][i].first] > dist[nd] + G[nd][i].second) {
dist[G[nd][i].first] = dist[nd] + G[nd][i].second;
coada.push(G[nd][i].first);
}
}
}
if (dist[nod] < 0) {
g << "Ciclu negativ!";
exit(0);
}
}
int main()
{
f >> n >> m;
for (int i = 1; i <= m; i++) {
int x, y, cost;
f >> x >> y >> cost;
G[x].push_back(make_pair(y, cost));
}
for (int i = 2; i <= n; i++) {
bfs(i);
}
bfs(1);
for (int i = 2; i <= n; i++) {
g << dist[i] << ' ';
}
return 0;
}