Cod sursa(job #2888673)

Utilizator Maria-BorcaBorca Maria Maria-Borca Data 11 aprilie 2022 18:51:57
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>

using namespace std;
string file1 = "date.in";
string file2 = "ascii.in";

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

int graph[1005][1005], n, m, dist[1005], previous[1005];

void citire() {
    int x, y, z;
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        fin >> x >> y >> z;
        graph[x][y] = z;
    }
}

void graphic(ifstream &inputFile, string fileName) {
    string content;
//    inputFile.open(fileName);
    while (getline(inputFile, content)) {
        cout << content << endl;
        cout << content.size();
    }
    cout << endl << endl;
    inputFile.close();
}

bool bellmanFord(int start) {
    for (int i = 1; i <= n; i++) {
        dist[i] = 100000000;
        previous[i] = 0;
    }
    dist[start] = 0;
    for (int nod = 1; nod < n; nod++) {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (graph[i][j] != 0 && dist[j] > dist[i] + graph[i][j]) {
                    dist[j] = dist[i] + graph[i][j];
                    previous[j] = i;
                }
            }
        }
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (graph[i][j] != 0 && dist[j] > dist[i] + graph[i][j]) {
                cout << "Ciclu negativ!";
                return false;
            }
        }
    }
    return true;
}

int main() {
    citire();
    if (bellmanFord(1))
        for (int i = 2; i <= n; i ++)
            fout << dist[i] << ' ';
    return 0;
}