Cod sursa(job #979810)

Utilizator manutrutaEmanuel Truta manutruta Data 2 august 2013 20:49:48
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
# include <cstdlib>
# include <cstring>
# include <iostream>
# include <fstream>
# include <vector>
# include <queue>
# include <bitset>
using namespace std;

# define INF 0x3f3f3f3f
# define MAXN 50010
# define MAXM 250010

ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

struct muchie {
    int id, cost;
};

int n, m;
vector<pair<int, muchie> > G[MAXN];
int dist[MAXN];
queue<int> coada;
bitset<MAXM> vizmuchie;

void bfs(int nod = 1)
{
    bool ok = true;
    memset(dist, 0x3f, sizeof(dist));
    dist[nod] = 0;
    coada.push(nod);
    while (!coada.empty() && ok == true) {
        int nd = coada.front();
        coada.pop();

        for (int i = 0; i < G[nd].size(); i++) {
            if (dist[G[nd][i].first] > dist[nd] + G[nd][i].second.cost) {
                dist[G[nd][i].first] = dist[nd] + G[nd][i].second.cost;
                coada.push(G[nd][i].first);
                if (vizmuchie[G[nd][i].second.id] == false) {
                    vizmuchie[G[nd][i].second.id] = true;
                } else if (dist[G[nd][i].first] < -50000000) {
                    ok = 0;
                }
            }
        }
    }

    if (ok == false) {
        g << "Ciclu negativ!";
        exit(0);
    }
    for (int i = 2; i <= n; i++) {
        g << dist[i] << ' ';
    }
}

int main()
{
    f >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y;
        muchie m;
        f >> x >> y >> m.cost;
        m.id = i;
        G[x].push_back(make_pair(y, m));
    }

    bfs();

    return 0;
}