Pagini recente » Cod sursa (job #1934411) | Cod sursa (job #1832986) | Cod sursa (job #2601257) | Cod sursa (job #1313482) | Cod sursa (job #898586)
Cod sursa(job #898586)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int maxn = 50001;
const int maxm = 250001;
const int inf = 0x7ffffff;
int N, M, dist[maxn], count[maxn];
struct edge {
edge(int u, int v, int c) { this->u = u; this->v = v; this->c = c; }
int u, v, c;
};
vector<edge> E;
vector<int> v[maxn]; // muchia i incidenta cu nodul E[i].u
queue<int> qu; // coada nodurilor
bitset<maxn> in_qu;
int main()
{
int p, q, w; E.reserve(maxm); bool negative = false;
in >> N >> M;
for (int i = 0; i < M; i++)
{
in >> p >> q >> w;
E.push_back(edge(p, q, w));
v[ E[i].u ].push_back(i);
}
for (int i = 2; i <= N; i++) dist[i] = inf; // 1 e nodul sursa | dist[1] == 0
qu.push(1);
while(!qu.empty() && !negative)
{
int front = qu.front(); qu.pop();
in_qu[front] = false;
for (int i = 0; i < v[front].size(); i++)
{
int pos = v[front][i];
if ( dist[ E[pos].u ] + E[pos].c < dist[ E[pos].v ] )
{
dist[ E[pos].v ] = dist[ E[pos].u ] + E[pos].c;
if (!in_qu[ E[pos].v ])
{
if (count[ E[pos].v ] > N) {
negative = true; continue;
}
else {
qu.push(E[pos].v);
in_qu[ E[pos].v ] = true;
count[ E[pos].v ]++;
}
}
}
}
}
if (!negative) {
for (int i = 2; i <= N; i++)
out << dist[i] << ' ';
}
else out << "Ciclu negativ!";
return 0;
}