Cod sursa(job #1375301)

Utilizator MarronMarron Marron Data 5 martie 2015 12:55:56
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.14 kb
#include <cstring>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>


typedef std::vector< std::pair<int, int> >::iterator iter;


const int MAXN = 50005;
const int MAXM = 250005;
const int INF = 0x3f3f3f3f;
// <parsing>
const int MAXB = 8192;
FILE* f = fopen("bellmanford.in", "r");
char buf[MAXB]; int ptr = MAXB;
int getInt()
{
    int mul = 1;
    while (buf[ptr] < '0' || '9' < buf[ptr]) {
        if (buf[ptr] == '-') {
            mul = -1;
        }
        if (++ptr >= MAXB) {
            fread(buf, MAXB, 1, f);
            ptr = 0;
        }
    }
    int nr = 0;
    while ('0' <= buf[ptr] && buf[ptr] <= '9') {
        nr = nr * 10 + buf[ptr] - '0';
        if (++ptr >= MAXB) {
            fread(buf, MAXB, 1, f);
            ptr = 0;
        }
    }
    return mul * nr;
}
// </parsing>
std::ofstream g("bellmanford.out");
std::vector< std::pair<int, int> > G[MAXN]; int n, m;
std::priority_queue< std::pair<int, int> > pq;
int dist[MAXN], viz[MAXN];


void bellmanford()
{
    memset(dist, 0x3f, sizeof(dist));
    memset(viz, 0, sizeof(viz));
    dist[1] = 0;

    bool ok = true;
    pq.push(std::make_pair(0, 1));
    while (!pq.empty()) {
        int nd = pq.top().second;
        int d = -pq.top().first;
        pq.pop();

        viz[nd]++;
        if (viz[nd] > n) {
            ok = false;
            break;
        }

        for (iter it = G[nd].begin(); it != G[nd].end(); it++) {
            if (dist[it->first] > dist[nd] + it->second) {
                dist[it->first] = dist[nd] + it->second;
                pq.push(std::make_pair(-dist[it->first], it->first));
            }
        }
    }

    if (!ok) {
        g << "Ciclu negativ!" << std::endl;
        return;
    }

    for (int i = 2; i <= n; i++) {
        g << dist[i] << ' ';
    }
    g << std::endl;
}


int main()
{
    n = getInt(); m = getInt();
    for (int i = 1, x, y, c; i <= m; i++) {
        x = getInt(); y = getInt(); c = getInt();
        G[x].push_back(std::make_pair(y, c));
    }


    bellmanford();


    fclose(f);
    g.close();
    return 0;
}