Cod sursa(job #2564883)

Utilizator vlad082002Ciocoiu Vlad vlad082002 Data 2 martie 2020 10:50:22
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

const int inf = 1000000000;
int n, m, dist[50005], nraparitii[50005];
bool inQueue[50005];
vector<pair<int, int> > g[50005];
bool cycle = false;

void citire() {
    fin >> n >> m;
    int a, b, c;
    while(m--) {
        fin >> a >> b >> c;
        g[a].push_back({b, c});
    }
}

void bellmanford() {
    for(int i = 1; i <= n; i++)
        dist[i] = inf;
    dist[1] = 0;
    for(int k = 1; k < n; k++)
        for(int i = 1; i <= n; i++)
            for(int j = 0; j < g[i].size(); j++)
                if(dist[i] + g[i][j].second < dist[g[i][j].first])
                    dist[g[i][j].first] = dist[i]+g[i][j].second;

    for(int i = 1; i <= n; i++)
        for(int j = 0; j < g[i].size(); j++)
            if(dist[i] + g[i][j].second < dist[g[i][j].first]) {
                fout << "Ciclu negativ!";
                return;
            }
    for(int i = 2; i <= n; i++)
        fout << dist[i] << ' ';
}

void bellmanfordqueue() {
    for(int i = 1; i <= n; i++)
        dist[i] = inf;
    dist[1] = 0;
    queue<int> q;
    q.push(1);
    inQueue[1] = 1;

    while(!q.empty() && !cycle) {
        int curr = q.front();
        inQueue[curr] = false;
        q.pop();
        for(int i = 0; i < g[curr].size(); i++)
            if(dist[curr] + g[curr][i].second < dist[g[curr][i].first]) {
                dist[g[curr][i].first] = dist[curr] + g[curr][i].second;
                if(!inQueue[g[curr][i].first]) {
                        if(nraparitii[g[curr][i].first] > n)
                            cycle = true;
                        else {
                            q.push(g[curr][i].first);
                            inQueue[g[curr][i].first] = true;
                            nraparitii[g[curr][i].first]++;
                        }
                }
            }
    }
    if(cycle)
        fout << "Ciclu negativ!";
    else
        for(int i = 2; i <= n; i++)
            fout << dist[i] << ' ';
}

int main() {
    citire();
    bellmanfordqueue();
}