Cod sursa(job #3126069)

Utilizator calin06calin mihaescu calin06 Data 5 mai 2023 18:32:08
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>
using namespace std;

const int inf = INT_MAX;
int n,m,c,m1,m2;
vector<vector<pair<int,int>>>adj(50010);
vector<bool>viz(50010,0);
vector<int>dist(50010,inf);
vector<int>fr(50010);

int BellmanFord(int nod)
{
    queue<int>q;
    dist[nod] = 0;
    q.push(nod);
    viz[nod] = 1;
    while(!q.empty())
    {
        int el = q.front();
        q.pop();
        viz[el] = 0;
        fr[el]++;
        if(fr[el] > n)
            return 0;

        for(int i = 0; i < adj[el].size(); i++)
        {
            int vecin = adj[el][i].first;
            int cost = adj[el][i].second;
            if(dist[el] + cost < dist[vecin])
            {
                dist[vecin] = dist[el] + cost;
                if(viz[vecin] == 0)
                {
                    viz[vecin] == 1;
                    q.push(vecin);
                }
            }
        }
    }
    return 1;
}

int main()
{
    ifstream cin("bellmanford.in");
    ofstream cout("bellmanford.out");
    cin>>n>>m;
    for(int i = 1; i <= m; i++)
    {
        cin>>m1>>m2>>c;
        adj[m1].push_back(make_pair(m2,c));
    }

    if(BellmanFord(1) == 0)
        cout<<"Ciclu negativ!";
    else
        for(int i = 2; i <= n; i++)
            cout<<dist[i]<<" ";
}