Cod sursa(job #2982570)

Utilizator PingStrpewpewpac PingStr Data 20 februarie 2023 14:56:03
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <bits/stdc++.h>
using namespace std;

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

const int SIZE = 50001;
const int INF = 1e9;

struct compare
{
    bool operator()(pair<int,int> l, pair<int, int> r)
    {
        return l.second > r.second;
    }
};

priority_queue<pair<int,int>, vector<pair<int,int>>, compare> qu;
vector<pair<int, int>> gr[SIZE];
vector<int> dist(SIZE, INF);
int n, m, x, y, z;
bool ok = 1, schimbari;

void bllmn(int stnd)
{
    dist[stnd] = 0;
    qu.push(make_pair(stnd, dist[stnd]));
    for (int i = 1; i <= n; i++)
    {
        schimbari = 0;
        qu.push(make_pair(stnd, dist[stnd]));
        while (!qu.empty())
        {
            int nod = qu.top().first;
            int distanta = qu.top().second;
            qu.pop();
            if (!(distanta > dist[nod]))
            {
                for (auto j: gr[nod])
                {
                    int vec = j.first;
                    int cost = j.second;
                    if (dist[nod] + cost < dist[vec])
                    {
                        dist[vec] = dist[nod] + cost;
                        qu.push(make_pair(vec, dist[vec]));
                        schimbari = 1;
                    }
                    if ((dist[nod] + cost < dist[vec]) && i > n)
                    {
                        int ok = 0;
                        fout<<"Ciclu negativ!";
                        return;
                    }
                }
            }
        }
        if (schimbari == 0)
            return;
    }
}

int main()
{
    fin>>n>>m;
    for (int i = 1; i <= m; i++)
    {
        fin>>x>>y>>z;
        gr[x].push_back(make_pair(y, z));
    }
    bllmn(1);
    if (ok)
    {
        for (int i = 2; i <= n; i++)
        {
                fout<<dist[i]<<" ";
        }
    }
}