Cod sursa(job #2425469)

Utilizator MateiAruxandeiMateiStefan MateiAruxandei Data 24 mai 2019 20:39:56
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include<bits/stdc++.h>

using namespace std;

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

const int INF = 0x3f3f3f3f;

vector<pair<int, int > > G[50005];
bool waiting[50005];
int cost[50005], times[50005];

int main()
{
    int n, m;
    fin >> n >> m;

    for(int i = 1; i <= m; ++i)
    {
        int x, y, c;
        fin >> x >> y >> c;

        G[x].push_back({y, c});
    }

    for(int i = 2; i <= n; ++i)
        cost[i] = INF;

    bool negativeCy = 0;
    queue<int> q;
    q.push(1);
    waiting[1] = true;
    times[1] = 1;
    while(!q.empty() && !negativeCy)
    {
        auto p = q.front();
        q.pop();

        waiting[p] = false;
        for(auto it : G[p])
        {
            if(cost[it.first] > cost[p] + it.second)
            {
                cost[it.first] = cost[p] + it.second;
                if(waiting[it.first] == false)
                {
                    if(times[it.first] > n)
                        negativeCy = true;
                    else
                    {
                        q.push(it.first);
                        waiting[it.first] = 1;
                        times[it.first] ++;
                    }
                }
            }
        }
    }

    if(negativeCy)
        fout << "Ciclu negativ!\n";
    else {
        for(int i = 2; i <= n; ++i)
            fout << cost[i] << ' ';
        fout << '\n';
    }
    return 0;
}