Pagini recente » Cod sursa (job #3178792) | Cod sursa (job #2272925) | Cod sursa (job #672286) | Cod sursa (job #1702401) | Cod sursa (job #2121674)
//Stan Antoniu
//In acest program folosesc STL prima data, deci va fi un bun suport teoretic.
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <climits>
#define maxn 50002
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector <pair <int, int> > adj[maxn]; // lista de adiacenta fara pointeri
vector <int> dist(maxn, INT_MAX); //costul minim al unui lant de la 1 la nodul i
vector <int> count_in_queue(maxn, 0); //numara de cate ori un nod a intrat in coada
queue <int> q;
bitset <maxn> in_queue(false); //0 => nodul nu e in coada; 1 => nodul e in coada
int n, m;
void read()
{
int x, y, c;
fin >> n >> m;
for (int i = 0; i < m; i++) {
fin >> x >> y >> c;
adj[x].push_back(make_pair(y, c));
}
}
int main()
{
int negativ = 0, aux;
vector < pair <int, int> >::iterator it; //iterator
read();
dist[1] = 0;
q.push(1);
in_queue[1].flip(); //echivalent in_queue[1] = true
while (!q.empty() && !negativ) {
aux = q.front();
q.pop();
in_queue[aux] = false;
for (it = adj[aux].begin(); it != adj[aux].end(); it++)
if (dist[aux] < INT_MAX && dist[it -> first] > dist[aux] + it -> second) {
dist[it->first] = dist[aux] + it->second;
if (!in_queue[it -> first]) {
if (count_in_queue[it -> first] > n) // conditie de ciclu negativ
negativ = 1;
else {
q.push(it -> first);
in_queue[it -> first] = true;
count_in_queue[it -> first]++;
}
}
}
}
if (negativ == 1)
fout << "Ciclu negativ!\n";
else {
for (int i = 2; i <= n; i++)
fout << dist[i] << ' ';
}
return 0;
}