Cod sursa(job #1845582)

Utilizator GoogalAbabei Daniel Googal Data 11 ianuarie 2017 18:00:55
Problema Algoritmul Bellman-Ford Scor 65
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <fstream>
#include <vector>
#define nmax 50001
#define INF 1<<30

using namespace std;

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

int n,m,cost[nmax];
bool viz[nmax],ok=true,kappa;

vector < pair < int, int > > leg[nmax];

inline void read()
{
    int i,a,b,c;
    fin>>n>>m;
    for(i=2; i<=n; i++)
        cost[i]=INF;
    for(i=1; i<=m; i++)
    {
        fin>>a>>b>>c;
        leg[a].push_back(make_pair(b,c));
    }
    fin.close();
}

inline void bellford()
{
    int i,rd,j;

    for(rd=1; rd<n; rd++)
    {
        kappa=false;
        for(i=1; i<=n; i++)
        {
            if(viz[i]==false)
            {
                viz[i]=true;
                for(j=0; j<leg[i].size(); j++)
                {
                    if(cost[leg[i][j].first]>cost[i]+leg[i][j].second)
                    {
                        cost[leg[i][j].first]=cost[i]+leg[i][j].second;
                        viz[leg[i][j].first]=false;
                        kappa=true;
                    }
                }
            }
        }
        if(kappa==false)
            break;
    }
    if(kappa==true)
    {
        for(i=1; i<=n; i++)
        {
            if(viz[i]==false)
            {
                for(j=0; j<leg[i].size(); j++)
                {
                    if(cost[leg[i][j].first]>cost[i]+leg[i][j].second)
                    {
                        ok=false;
                        break;
                    }
                }
            }
        }
    }
}

inline void write()
{
    if(ok==false)
        fout<<"Ciclu negativ!";
    else
    {
        for(int i=2; i<=n; i++)
            fout<<cost[i]<<' ';
    }

    fout.close();
}

int main()
{
    read();
    bellford();
    write();
    return 0;
}