Pagini recente » Cod sursa (job #1275193) | Cod sursa (job #1826059) | Cod sursa (job #1513574) | Cod sursa (job #2187868) | Cod sursa (job #3186012)
#include <fstream>
#include <vector>
#include <queue>
#define Nmax 500002
#define Mmax 250002
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
int n, m;
vector<pair<int, int>> mat[Nmax];
queue<int> q;
vector<int> dist(Nmax, 1e9);
int viz[Nmax], cnt[Nmax];
void citire()
{
cin >> n >> m;
for(int i = 0, a, b, c; i<m; i++)
{
cin >> a >> b >> c;
mat[a].push_back({b, c});
}
}
void Bellman_Ford()
{
for(int i = 1; i<=n; i++)
dist[i] = 1e9;
dist[1] = 0;
q.push(1);
//viz[1] = 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)
{
cout << "Ciclu negativ!";
exit(0);
}
}
}
}
}
}
void afisare()
{
for(int i = 2; i<=n; i++)
cout << dist[i] << ' ';
}
int main()
{
citire();
Bellman_Ford();
afisare();
}