Cod sursa(job #1158913)

Utilizator manutrutaEmanuel Truta manutruta Data 29 martie 2014 10:43:15
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <cstring>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

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

#define MAXN 50005

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

int n;
vector< pair<int, int> > G[MAXN];
queue<int> q;
int viz[MAXN], dist[MAXN];
bool ok = true;

void bf()
{
    memset(dist, 0x3f, sizeof(dist));
    dist[1] = 0;
    q.push(1);

    while (!q.empty()) {
        int nd = q.front();
        q.pop();

        viz[nd]++;
        if (viz[nd] > n) {
            ok = false;
            cout << nd << endl;
            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;
                q.push(it->first);
            }
        }
    }
}

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

    bf();

    if (ok == true) {
        for (int i = 2; i <= n; i++) {
            g << dist[i] << ' ';
        }
    } else {
        g << -1;
    }
    g << '\n';

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