Cod sursa(job #3268337)

Utilizator MegaCoderMinoiu Teodor Mihai MegaCoder Data 14 ianuarie 2025 17:19:28
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include<fstream>
#include<queue>
#include<vector>
#include<bitset>
#define INF 1000000000
std::ifstream fin("bellmanford.in");
std::ofstream fout("bellmanford.out");
const int NMAX=50005;
std::vector<std::pair<int, int>>G[NMAX];
std::vector<int>dist(NMAX, INF);
std::vector<int>cnt(NMAX);
std::bitset<NMAX>f;
int n, m;
void read()
{
    fin>>n>>m;
    for(int i=0; i<m; ++i)
    {
        int from, to, cost;
        fin>>from>>to>>cost;
        G[from].emplace_back(to, cost);
    }
}
void bellman_ford()
{
    dist[1]=0;
    f[1]=true;
    std::queue<int>q;
    q.push(1);
    while(!q.empty())
    {
        int node=q.front();
        q.pop();
        //f[node]=false;
        if(cnt[node]==n)
        {
            fout<<"Ciclu negativ!";
            std::exit(0);
        }

        for(auto it:G[node])
        {
            int y=it.first, cost=it.second;
            if(dist[y]>dist[node]+cost)
            {
                dist[y]=dist[node]+cost;
                ++cnt[y];

                    q.push(y);
            }
        }
    }

    for(int i=2; i<=n; ++i)
        fout<<dist[i]<<' ';
}
int main()
{
    read();
    bellman_ford();
    return 0;
}