Cod sursa(job #1375266)

Utilizator MarronMarron Marron Data 5 martie 2015 12:50:12
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 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;
std::ifstream f("bellmanford.in");
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()
{
    f >> n >> m;
    for (int i = 1, x, y, c; i <= m; i++) {
        f >> x >> y >> c;
        G[x].push_back(std::make_pair(y, c));
    }


    bellmanford();


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