Cod sursa(job #2848861)

Utilizator ioan_bogioan bogdan ioan_bog Data 14 februarie 2022 08:41:52
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <iostream>
#include <fstream>
#include <bitset>
#include<queue>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int t[3][250001],ciclu[50001],n,m,start[50001],c[50001];
int k=0,i,j,cost,prim,ultim,x,p,o;
bool ok=1;
bitset <50001>viz;
void initializare()
{
    int i,maxi=10000101;
    for(i=1;i<=n;i++)
         c[i]=maxi;
}

int main()
{

    f>>n>>m;
    for(o=1;o<=m;o++)
    {
        k++;
        f>>i>>j>>t[2][k];
        t[0][k]=j;
        t[1][k]=start[i];
        start[i]=k;
    }
    initializare();
    prim=ultim=1;
    c[1]=0;
    viz[1]=1;
    queue<int>q;
    q.push(1);
    while(!q.empty())
    {
       x=q.front();
       q.pop();
       ciclu[x]++;

        viz[x]=0;
        if(ciclu[x]>=n)
        {
            ok=0;
            break;
        }
        p=start[x];
        while(p)
        {
            if(c[x]+t[2][p]<c[t[0][p]])
            {
                c[t[0][p]]=c[x]+t[2][p];
                if(viz[t[0][p]]==0)
                {
                    viz[t[0][p]]=1;
                    q.push(t[0][p]);

                }
            }
            p=t[1][p];
        }

    }
    if(ok==0)
    {
        g<<"Ciclu negativ!";
    }
    else
    {
        for(o=2;o<=n;o++)
            g<<c[o]<<" ";
    }
    return 0;
}