Cod sursa(job #3252640)

Utilizator AndreiNicolaescuEric Paturan AndreiNicolaescu Data 30 octombrie 2024 13:41:23
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <queue>
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
vector<vector<pair<int, int>>> graf;
vector<int> inqueue, d, cnt;
const int INF = 0x3F3F3F3F;
int n, m, x, y, z;
int spfa(int node)
{
    queue<int> q;
    d[node] = 0;
    inqueue[node] = 1;
    q.push(node);
    while(!q.empty())
    {
        node = q.front();
        q.pop();
        inqueue[node] = 0;
        for(auto next:graf[node])
            if(d[next.first] > d[node] + next.second)
            {
                d[next.first] = d[node] + next.second;
                if(!inqueue[next.first])
                {
                    q.push(next.first);
                    inqueue[next.first] = 1;
                    cnt[next.first]++;
                    if(cnt[next.first] >= n)
                        return 0;
                }
            }
    }
    return 1;
}
int main()
{
    cin >> n >> m;
    graf.assign(n+1, vector<pair<int, int>>());
    cnt.resize(n+1);
    inqueue.resize(n+1);
    d.resize(n+1, INF);
    while(m--)
    {
        cin >> x >> y >> z;
        graf[x].push_back({y, z});
    }
    int node = spfa(1);
    if(!node)
        cout << "Ciclu negativ!";
    else
        for(int i=2; i<=n; i++)
            cout << d[i] << " ";
    return 0;
}