Cod sursa(job #979847)

Utilizator manutrutaEmanuel Truta manutruta Data 2 august 2013 22:25:46
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 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;

void bfs(int nod = 1)
{
    int nd = 0;

    memset(dist, 0x3f, sizeof(dist));
    dist[nod] = 0;

    coada.push(nod);
    while (!coada.empty() && dist[nd] >= (-1000) * G[nd].size()) {
        nd = coada.front();
        coada.pop();

        cout << dist[nd] << ' ' << G[nd].size() << endl;


        for (int i = 0; i < G[nd].size(); i++) {
            if (dist[G[nd][i].first] > dist[nd] + G[nd][i].second.cost) {
                //cout << dist[G[nd][i].first] << ' ' << dist[nd] << ' ';
                dist[G[nd][i].first] = dist[nd] + G[nd][i].second.cost;
                //cout << dist[G[nd][i].first] << '\n';
                coada.push(G[nd][i].first);
            }
        }
    }

    if (dist[nd] < (-1000) * G[nd].size()) {
        g << "Ciclu negativ!";
        exit(0);
    }
}

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();
    for (int i = 2; i <= n; i++) {
        g << dist[i] << ' ';
    }

    return 0;
}