Cod sursa(job #1777943)

Utilizator alexandru.jercaianuJercaianu Alexandru alexandru.jercaianu Data 13 octombrie 2016 02:55:03
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include<iostream>
#include<vector>
#include<fstream>
#include<queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

vector<vector<pair<int, int>>> g;
int n, m;

vector<int> cost;
vector<int> vis;

int bellman(int src)
{
    queue<int> q;
    q.push(src);
    cost[src] = 0;
    while (!q.empty()) {
        int node = q.front();
        vis[node]++;
        if (vis[node] >= n)
            return -1;
        q.pop();

        for (int i = 0; i < g[node].size(); i++) {
            auto p = g[node][i];
            if (cost[node] + p.second < cost[p.first]) {
                cost[p.first] = cost[node] + p.second;
                q.push(p.first);
            }
        }
    }
    return 0;
}

int main()
{
    fin >> n >> m;
    g.resize(n + 1);
    vis.resize(n + 1, 0);
    cost.resize(n + 1, numeric_limits<int>::max());

    for (int i = 0; i < m; i++) {
        int x, y, z;
        fin >> x >> y >> z;
        g[x].push_back(make_pair(y, z));
    }

    int res = bellman(1);
    if (res == 1) {
        fout << "Ciclu negativ!" << endl;
    } else {
        for (int i = 2; i < cost.size(); i++)
            fout << cost[i] << " ";
    }

    fout.close();
    fin.close();


}