Cod sursa(job #2068394)

Utilizator monicalMonica L monical Data 17 noiembrie 2017 18:54:45
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
//Drumuri minime de la varful s la oricare varf i - graful avand si arce de cost negativ
//40 puncte - Infoarena - O(n*m)

#include <cstdio>
#include<cstdlib>

using namespace std;

const int maxn = 50001;
const int inf = 1 << 30;

FILE *in = fopen("bellmanford.in","r"), *out = fopen("bellmanford.out","w");

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

int n, m;
graf *a[maxn];
int d[maxn], q[maxn];

void add(int where, int what, int cost)
{
    graf *q = new graf;
    q->nod = what;
    q->cost = cost;
    q->next = a[where];
    a[where] = q;
}

void read()
{
    fscanf(in, "%d %d", &n, &m);

    int x, y, z;
    for ( int i = 1; i <= m; ++i )
    {
        fscanf(in, "%d %d %d", &x, &y, &z);
        add(x, y, z);
    }
}

void bellman()
{
    for ( int i = 2; i <= n; ++i )
        d[i] = inf;

    int min, pmin = 0;
    for ( int i = 1; i <= n; ++i )
    {
        min = inf;

        for ( int j = 1; j <= n; ++j )
            if ( d[j] < min && !q[j] )
                min = d[j], pmin = j;

        q[pmin] = 1;

        graf *t = a[pmin];

        while ( t )
        {
            if ( d[ t->nod ] > d[pmin] + t->cost )
                d[ t->nod ] = d[pmin] + t->cost;

            t = t->next;
        }
    }

    for ( int i = 1; i <= n; ++i )
    {
       graf *t = a[i];

        while ( t )
        {
            if ( d[ t->nod ] > d[i] + t->cost )
                {
                    fprintf(out, "Ciclu negativ!");
                    exit(0);
                }

            t = t->next;
        }
    }
}

int main()
{
    read();
    bellman();

    for ( int i = 2; i <= n; ++i )
        fprintf(out, "%d ", d[i] == inf ? 0 : d[i]);
    fprintf(out, "\n");

    return 0;
}