Cod sursa(job #1766582)

Utilizator BlackNestaAndrei Manaila BlackNesta Data 28 septembrie 2016 09:14:24
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>
#define Nmax 50005
#define INF (1 << 30)

using namespace std;

struct muchie
{
    int nod, cost;
};

vector <muchie> L[Nmax];
bitset <Nmax> viz;
bool Negative;
int dist[Nmax], cnt[Nmax], n, m;
queue <int> q;

void Citire()
{
    ifstream f("bellmanford.in");
    f >> n >> m;
    muchie w;
    int x;
    for(int i = 1; i <= m; i++)
    {
        f >> x >> w.nod >> w.cost;
        L[x].push_back(w);
    }
    f.close();
}

void BellmanFord()
{
    for(int i = 1; i <= n; i++)
        dist[i] = INF;
    dist[1] = 0;
    viz[1] = 0;
    cnt[1] = 1;
    q.push(1);
    Negative = false;
    while(!q.empty() && Negative == false)
    {
        int nod = q.front();
        q.pop();
        viz[nod] = 1;
        for(unsigned i = 0; i < L[nod].size(); i++)
        {
            int j = L[nod][i].nod;
            int c = L[nod][i].cost;
            if(dist[j] > dist[nod] + c)
            {
                dist[j] = dist[nod] + c;
                if(viz[j] == 0)
                {
                    q.push(j);
                    viz[j] = 1;
                    cnt[j]++;
                    if(cnt[j] > n)
                        Negative = true;
                }
            }
        }
    }
}

void Afisare()
{
    ofstream g("bellmanford.out");
    if(Negative)
        g << "Ciclu negativ!";
    else
        for(int i = 2; i <= n; i++)
            g << dist[i] << " ";
    g << "\n";
    g.close();
}

int main()
{
    Citire();
    BellmanFord();
    Afisare();
    return 0;
}