Pagini recente » Cod sursa (job #482291) | Cod sursa (job #357558) | Cod sursa (job #65416) | Cod sursa (job #764202) | Cod sursa (job #3220557)
#include <fstream>
#include <vector>
#include <queue>
#define Nmax 500002
#define INF 1e9
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n, m;
vector<pair<int, int>> mat[Nmax];
queue<int> q;
vector<int> dist(Nmax, INF);
int viz[Nmax], cnt[Nmax];
void Bellman_Ford()
{
dist[1] = 0;
q.push(1);
while(!q.empty())
{
int k = q.front();
q.pop();
viz[k] = 0;
for(auto it : mat[k])
{
int cost = it.second;
int dest = it.first;
if(dist[k] + cost < dist[dest])
{
dist[dest] = dist[k] + cost;
if(viz[dest] == 0)
{
viz[dest] = 1;
q.push(dest);
cnt[dest]++;
if(cnt[dest] > n)
{
g << "Ciclu negativ!";
exit(0);
}
}
}
}
}
}
int main()
{
f >> n >> m;
int a, b, c;
for(int i = 1; i <= m; i++)
{
f >> a >> b >> c;
mat[a].push_back({b, c});
}
for(int i = 1; i <= n; i++)
dist[i] = INF;
Bellman_Ford();
for(int i = 2; i <= n; i++)
g << dist[i] << ' ';
}