Pagini recente » Cod sursa (job #2808488) | Cod sursa (job #1301073) | Cod sursa (job #1625982) | Cod sursa (job #2715554) | Cod sursa (job #979847)
Cod sursa(job #979847)
# include <cstdlib>
# include <cstring>
# include <iostream>
# include <fstream>
# include <vector>
# include <queue>
# include <bitset>
using namespace std;
# define INF 0x3f3f3f3f
# define MAXN 50010
# define MAXM 250010
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
struct muchie {
int id, cost;
};
int n, m;
vector<pair<int, muchie> > G[MAXN];
int dist[MAXN];
queue<int> coada;
void bfs(int nod = 1)
{
int nd = 0;
memset(dist, 0x3f, sizeof(dist));
dist[nod] = 0;
coada.push(nod);
while (!coada.empty() && dist[nd] >= (-1000) * G[nd].size()) {
nd = coada.front();
coada.pop();
cout << dist[nd] << ' ' << G[nd].size() << endl;
for (int i = 0; i < G[nd].size(); i++) {
if (dist[G[nd][i].first] > dist[nd] + G[nd][i].second.cost) {
//cout << dist[G[nd][i].first] << ' ' << dist[nd] << ' ';
dist[G[nd][i].first] = dist[nd] + G[nd][i].second.cost;
//cout << dist[G[nd][i].first] << '\n';
coada.push(G[nd][i].first);
}
}
}
if (dist[nd] < (-1000) * G[nd].size()) {
g << "Ciclu negativ!";
exit(0);
}
}
int main()
{
f >> n >> m;
for (int i = 1; i <= m; i++) {
int x, y;
muchie m;
f >> x >> y >> m.cost;
m.id = i;
G[x].push_back(make_pair(y, m));
}
bfs();
for (int i = 2; i <= n; i++) {
g << dist[i] << ' ';
}
return 0;
}