Cod sursa(job #2606437)

Utilizator pregoliStana Andrei pregoli Data 27 aprilie 2020 19:22:55
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>
#define newline '\n'
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
///***********************
#define neighbour first
#define cost second
const int OO = 0x3f3f3f3f;
const int NMAX = 5e4 + 3;
int n, m;
array<vector<pair<int, int>>, NMAX> lst;
array<int, NMAX> dis, nrVis;
array<bool, NMAX> inQ;

void read()
{
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, z;
        fin >> x >> y >> z;
        lst[x].push_back(make_pair(y, z));
    }
}

bool bellmanFord(int start)
{
    fill(dis.begin(), dis.end(), OO);
    dis[start] = 0;
    inQ[start] = true;
    queue<int> q;
    q.push(start);

    while (!q.empty())
    {
        int cnode = q.front();
        q.pop();
        nrVis[cnode]++;
        if (nrVis[cnode] >= n)
            return false;
        inQ[cnode] = false;

        for (auto it : lst[cnode])
        {
            if (dis[cnode] + it.cost < dis[it.neighbour])
            {
                dis[it.neighbour] = dis[cnode] + it.cost;
                if (!inQ[it.neighbour])
                {
                    q.push(it.neighbour);
                    inQ[it.neighbour] = true;
                }
            }
        }
    }
    return true;
}

void display(bool hasCy)
{
    if (hasCy)
        fout << "Ciclu negativ!" << newline;
    else
        for (int i = 2; i <= n; i++)
            fout << dis[i] << ' ';
}

int main()
{
    read();
    display(!bellmanFord(1));
    fout.close();
    return 0;
}