Pagini recente » Cod sursa (job #3154431) | Cod sursa (job #2506134) | Cod sursa (job #2713982) | Cod sursa (job #377370) | Cod sursa (job #2418070)
#include <fstream>
#include <vector>
#include <queue>
#define INF 1000000000
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
vector<int> d;
struct edge
{
int x, y, c;
};
struct mycomp
{
bool operator() (int &a, int &b)
{
return d[a] > d[b];
}
};
int main()
{
int n, m;
in >> n >> m;
vector<edge> edges;
vector<pair<int,int>> v[n+1];
for(int i = 0; i < m; i++)
{
int x, y, c;
in >> x >> y >> c;
edge e = {x,y,c};
edges.push_back(e);
v[x].push_back({y,c});
}
d.assign(n+1,INF);
d[1] = 0;
priority_queue<int,vector<int>,mycomp> pq;
pq.push(1);
vector<bool> inQ(n+1,false);
for(int i = 1; i < n; i++)
{
int nod = pq.top();
pq.pop();
inQ[nod] = false;
for(int j = 0; j < v[nod].size(); j++)
{
int act = v[nod][j].first;
int cost = v[nod][j].second;
if(d[nod]+cost < d[act])
{
d[act] = d[nod]+cost;
if(!inQ[act])
{
inQ[act] = true;
pq.push(act);
}
}
}
}
for(int i = 1; i <= n; i++)
for(size_t j = 0; j < edges.size(); j++)
{
int x = edges[j].x;
int y = edges[j].y;
int c = edges[j].c;
if(d[x]+c < d[y])
{
out << "Ciclu negativ!";
return 0;
}
}
for(int i = 2; i <= n; i++) out << d[i] << ' ';
return 0;
}