Pagini recente » Cod sursa (job #1373368) | Cod sursa (job #2352074) | Cod sursa (job #3131653) | Cod sursa (job #375244) | Cod sursa (job #1337729)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream is("bellmanford.in");
ofstream os("bellmanford.out");
int n, m;
vector<vector<pair<int,int> > > G;
queue<int> q;
bool inq[50001];
int aux1, aux2, aux3;
int d[50001];
int cnt[50001];
void BellmanFord();
int main()
{
is >> n >> m;
G.resize(n+1);
for(int i = 1; i <= n; ++i)
d[i] = 0x3f3f3f3f;
d[1] = 0;
q.push(1);
inq[1] = true;
for(int i = 1; i <= m; ++i)
{
is >> aux1 >> aux2 >> aux3;
G[aux1].push_back(make_pair(aux2, aux3));
}
BellmanFord();
for(int i = 2; i <= n; ++i)
{
os << d[i] << ' ';
}
is.close();
os.close();
return 0;
}
void BellmanFord()
{
int x;
int vec;
int cost;
while(!q.empty())
{
x = q.front();
q.pop();
inq[x] = 0;
for(const auto& i : G[x])
{
vec = i.first;
cost = i.second;
if(d[vec] > d[x] + cost)
{
d[vec] = d[x] + cost;
if(!inq[vec])
{
cnt[vec]++;
if(cnt[vec] == n)
{
os << "ciclu negativ";
return;
}
q.push(vec);
inq[vec] = true;
}
}
}
}
}