Pagini recente » Cod sursa (job #317230) | Cod sursa (job #90915) | Cod sursa (job #1456059) | Cod sursa (job #3229687) | Cod sursa (job #2691807)
/*#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <algorithm>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int nmax = 50005;
const int val_mare = 0x3f3f3f3f;
vector < pair <int, int> > list_vec[nmax];
int main() {
int n, m, u, v, c;
fin >> n >> m;
for (int i = 0; i < m; ++ i) {
fin >> u >> v >> c;
list_vec[u].push_back({v, c});
}
queue <int> q;
bitset <nmax> in_coada(false);
vector <int> dist(nmax, val_mare), contor_in_coada(nmax, 0);
int negative_cycle = false, curent, vecin, cost;
dist[1] = 0, q.push(1), in_coada[1] = 1;
while (!q.empty() && !negative_cycle)
{
curent = q.front();
q.pop();
in_coada[curent] = false;
for (auto it : list_vec[curent])
{
if (dist[curent] < val_mare)
{
vecin = it.first;
cost = it.second;
if (dist[vecin] > dist[curent] + cost)
{
dist[vecin] = dist[curent] + cost;
if (!in_coada[vecin])
{
if (contor_in_coada[vecin] > n)//daca am ajuns sa punem in coada un element de mai mult de n ori
negative_cycle = true;
else
{
q.push(vecin);
in_coada[vecin] = true;
contor_in_coada[vecin] ++;
}
}
}
}
}
}
if (!negative_cycle) {
for (int i = 2; i <= n; ++ i)
fout << dist[i] << " ";
}
else
fout << "Ciclu negativ!\n";
return 0;
}
*/
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#include <bitset>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m, ok;
const int nmax = 50005, val_mare = 0x3f3f3f3f;
int negative_cycle;
vector<pair<int, int> > list_vec[nmax];
int dist[nmax], contor_in_coada[nmax];
void bellman_ford_q(int start)
{
queue <int> q;
bitset <nmax> in_coada(false);
int i;
//vector <int> dist(MAX_N, INF), in_coada(MAX_N, 0);
for(i = 1; i <= n; ++i)
dist[i] = val_mare;
dist[start] = 0;
q.push(start);
in_coada[start] = 1;
int curent, vecin, cost;
while (!q.empty() && !negative_cycle)
{
curent = q.front();
q.pop();
in_coada[curent] = false;
for(auto it : list_vec[curent])
{
if(dist[curent] < val_mare)
{
vecin = it.first;
cost = it.second;
if (dist[vecin] > dist[curent] + cost)
{
dist[vecin] = dist[curent] + cost;
if (!in_coada[vecin])
{
if (contor_in_coada[vecin] > n)
negative_cycle = true;
else
{
q.push(vecin);
in_coada[vecin] = true;
contor_in_coada[vecin]++;
}
}
}
}
}
}
}
int main()
{
int u, v, c, i;
fin>>n>>m;
for(i = 1; i <= m; ++i)
{
fin>>u>>v>>c;
list_vec[u].push_back({v, c});
}
bellman_ford_q(1);
if(negative_cycle)
fout<<"Ciclu negativ!";
else
{
for(i = 2; i <= n; ++i)
fout<<dist[i]<<' ';
}
return 0;
}