Cod sursa(job #3271884)

Utilizator cezarinfoTulceanu Cezar cezarinfo Data 27 ianuarie 2025 17:49:58
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include<iostream>
#include<fstream>
#include<vector>
#include<cstring>
#include<queue>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int NMAX=50005;
const int MMAX=250007;
const int INF=1000000009;
int n,m,a,b,c,i;
int cost[NMAX];
bool change=0;
bool good;
struct ed
{
    int x,y,w;
};
ed aux;
queue<int> q;
bool inn[NMAX];
vector<ed> adj[NMAX];
int rep[NMAX];
int main()
{

    in>>n>>m;
    for(i=1;i<=m;i++)
    {
        in>>a>>b>>c;
        aux.x=a;
        aux.y=b;
        aux.w=c;
        adj[a].push_back(aux);
    }
    memset(cost,INF,sizeof(cost));
    cost[1]=0;
    good=0;
    q.push(1);
    inn[1]=1;
    while(!q.empty())
    {
        int node=q.front();
        q.pop();
        inn[node]=0;
        for(auto g:adj[node])
        {
            if(cost[g.y]>cost[g.x]+g.w)
            {
                cost[g.y]=cost[g.x]+g.w;
                if(inn[g.y]==0)
                {
                    q.push(g.y);
                }
                rep[g.y]++;
                if(rep[g.y]==n+1)
                {
                    out<<"Ciclu negativ!";
                    return 0;
                }
            }
        }
    }
    for(i=2;i<=n;i++)
    {
        out<<cost[i]<<" ";
    }
}