Cod sursa(job #803520)

Utilizator TeodoraTanaseTeodora Tanase TeodoraTanase Data 27 octombrie 2012 18:51:56
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <cstdio>
#include <vector>
#include <queue>

#define NMAX 50001
#define INF 999999999

using namespace std;

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

struct nod
{
    int v;
    int cost;
};

int n;
int nr[NMAX];
int cost[NMAX];

struct comp
{
    bool operator () (const int &a, const int &b) const
    {
        return cost[a] > cost[b];
    }
};

vector <nod> G[NMAX];
priority_queue <int, vector <int>, comp> Q;

void read()
{
    int m;
    int x;
    nod y;

    fscanf (inFile, "%d %d\n", &n, &m);
    while (m --)
    {
        fscanf (inFile, "%d %d %d\n", &x, &y.v, &y.cost);
        G[x].push_back(y);
    }
}

bool bellmanford()
{
    for (int i = 2; i <= n; cost[i] = INF, ++ i);

    Q.push(1);
    while (!Q.empty())
    {
        int v = Q.top();
        Q.pop();

        for (unsigned int i = 0; i < G[v].size(); ++ i)
        {
            nod aux = G[v][i];

            if (cost[v] + aux.cost < cost[aux.v])
            {
                cost[aux.v] = cost[v] + aux.cost;
                Q.push(aux.v);
                ++ nr[v];
            }
        }

        if (nr[v] > n)
            return 0;
    }

    return 1;
}

void write()
{
    for (int i = 2; i <= n; ++ i)
        if (cost[i] == INF)
            fprintf (outFile, "0 ");
        else
            fprintf (outFile, "%d ", cost[i]);

    fprintf (outFile, "\n");
}

int main()
{
    read();
    if (!bellmanford())
        fprintf (outFile, "Ciclu negativ!");
    else
        write();

    return 0;
}