Cod sursa(job #2750200)

Utilizator andrei.florea0405Florea Andrei-Bogdan andrei.florea0405 Data 10 mai 2021 10:53:55
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.47 kb
#include <bits/stdc++.h>
using namespace std;

const int kNmax = 100005;

class Task {
public:
    void solve() {
           read_input();
           get_result();
}

private:
    int n;
	int m;
	vector<pair<int, int>> adj[kNmax];
    int source;

	void read_input() {
		ifstream fin("bellmanford.in");
		fin >> n >> m;
		for (int i = 1, x, y, c; i <= m; i++) {
			fin >> x >> y >> c;
			adj[x].push_back(make_pair(y, c));
		}
        //fin >> source;
		fin.close();
	}


    void get_result() {
        vector<int> distances(n + 1, INT_MAX);    
        vector<bool> flag(n + 1, false);
        vector<int> count_in_queue(n + 1, 0);

        source = 1;
        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
        
        pq.push(make_pair(0, source));
        distances[source] = 0;
        flag[source] = true;
        
        bool negative_cycle = false;

        while (!pq.empty() && !negative_cycle) {
            pair<int, int> top = pq.top();
            pq.pop();

            int node = top.second;
            int cost = top.first;

            flag[node] = false;

            for (auto &neigh_pair : adj[node]) {
                int neigh = neigh_pair.first;
                int edgeCost = neigh_pair.second;

                if (distances[neigh] > cost + edgeCost) {
                    distances[neigh] = cost + edgeCost;
                    if (!flag[neigh]) {
                        if (count_in_queue[neigh] > n) {
                            negative_cycle = true;
                            break;
                        } else {
                            flag[neigh] = true;
                            pq.push(make_pair(distances[neigh], neigh));
                            count_in_queue[neigh]++;
                        }
                    }
                }
            }
        }

        if (negative_cycle) {
            ofstream fout("bellmanford.out");
            fout << "Ciclu negativ!\n";
            fout.close();
        } else {
            print_output(distances);
        }
    }
       

    void print_output(vector<int> distances) {
        ofstream fout("bellmanford.out");
        
        for (int i = 2; i <= n; i++) {
            int d = distances[i];
            if (d == INT_MAX) {
                fout << "-1 ";
            } else {
                fout << d << " ";
            }
        }
        
        fout.close();
    }
};


int main() {
    Task *task = new Task();
    task->solve();
    delete task;
    return 0;
}