Pagini recente » Cod sursa (job #2607099) | Cod sursa (job #985634) | Cod sursa (job #145088) | Cod sursa (job #1603993) | Cod sursa (job #2966505)
#include <fstream>
#include <vector>
#include <utility>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int DIM = 50001;
const int INF = 260000000;
int n, m, x, y, c;
vector<pair<int, int>> adjList[DIM];
queue<int> q;
int inQueue[DIM], cost[DIM];
bool visited[DIM];
int main() {
fin >> n >> m;
for (int i = 1; i <= m; i++) {
fin >> x >> y >> c;
adjList[x].push_back(make_pair(y, c));
}
for (int i = 1; i <= n; i++)
cost[i] = INF;
q.push(1);
cost[1] = 0;
visited[1] = true;
inQueue[1] = 1;
while (!q.empty()) {
int node = q.front();
visited[node] = false;
q.pop();
for (auto adjElem : adjList[node]) {
int adjNode = adjElem.first, currCost = adjElem.second;
if (cost[adjNode] > cost[node] + currCost) {
cost[adjNode] = cost[node] + currCost;
if (!visited[adjNode]) {
inQueue[adjNode]++;
if (inQueue[adjNode] > n) {
fout << "Ciclu negativ!";
return 0;
}
q.push(adjNode);
visited[adjNode] = true;
}
}
}
}
for (int i = 2; i <= n; i++)
fout << cost[i] << ' ';
return 0;
}