Cod sursa(job #2163802)

Utilizator marcdariaDaria Marc marcdaria Data 12 martie 2018 20:01:55
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int Inf = 0x3f3f3f3f;

using PII = pair<int, int>;
using VI = vector<int>;
vector<PII> G[50005];
vector<int> d;
vector<int> nr;
vector<bool> v;
int N, M;

void Read();
int BellmanFord(int x, VI& d);
void Write();

int main()
{
    Read();
    BellmanFord(1, d);
    Write();

    return 0;
}

void Read()
{
    fin >> N >> M;
    d.resize(N + 1, Inf);
    v.resize(N + 1, false);
    nr.resize(N + 1);
    while(M--)
    {
        int x, y, cost;
        fin >> x >> y >> cost;
        G[x].push_back({y, cost});
    }
    fin.close();
}
int BellmanFord(int x, VI& d)
{
    d[x] = 0;
    v[x] = true;

    queue<int> Q;
    Q.push(x);
    while(!Q.empty())
    {
        int newx = Q.front();
        v[newx] = false;
        for(auto y : G[newx])
            if(d[newx] + y.second < d[y.first])
        {
            d[y.first] = d[newx] + y.second;
            if(!v[y.first])
            {
                if(nr[y.first] > N)
                {
                    fout << "Ciclu negativ!\n";
                    return 0;
                }

                Q.push(y.first);
                v[y.first] = true;
                ++nr[y.first];
            }
        }
        Q.pop();
    }
}
void Write()
{
    for(int i = 2; i <= N; ++i)
        fout << d[i] << " ";
    fout.close();
}