Cod sursa(job #2167547)

Utilizator RazorBestPricop Razvan Marius RazorBest Data 13 martie 2018 22:13:13
Problema Algoritmul Bellman-Ford Scor 15
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>
#include <algorithm>
#define oo 0x7fffffff
using namespace std;

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

struct graf
{
    int nod, c;
    graf *next;
};

struct muchie
{
    int x, y, c;
} M[250001];

int n, m, dist[50001], len;
graf * adj[50001];

struct noduri
{
    int a;
    bool operator<(const noduri x) const
    {
        return dist[a] > dist[x.a];
    }
} a[50001];



void add(int x, int y,  int c)
{
    graf *g = new graf;
    g->nod = y;
    g->c = c;
    g->next = adj[x];
    adj[x] = g;
}

bool bellman()
{
    for (int i = 1; i <= n; i++)
        dist[i] = oo;
    dist[1] = 0;

    a[0].a = 1;
    len = 1;
    while (len)
    {
        int nod = a[0].a, d = dist[nod];
        graf *q = adj[nod];
        while (q)
        {
            if (d + q->c < dist[q->nod])
            {
                dist[q->nod] = d + q->c;
                a[len++].a = q->nod;
            }
            q = q->next;
        }
        swap(a[0], a[len - 1]);
        len--;
        make_heap(a, a + len);
    }
    for (int j = 0; j < len; j++)
    {
        int nod = a[j].a, d = dist[nod];
        graf *q = adj[nod];
        while (q)
        {
            if (d + q->c < dist[q->nod])
                return false;
            q = q->next;
        }
    }


    return true;
}

int main()
{
    int x, y, c;

    fin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        fin >> x >> y >> c;
        add(x, y, c);
    }

    if(!bellman())
        fout << "Ciclu negativ!";
    else
        for (int i = 2; i <= n; i++)
            fout << dist[i] << ' ';

}