Cod sursa(job #1171859)

Utilizator darrenRares Buhai darren Data 16 aprilie 2014 15:03:44
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

const int INF = 0x3f3f3f3f;

int N, M;
vector<pair<int, int> > V[50002];
int D[50002], times[50002];
queue<int> Q;
bool inqueue[50002];

int main()
{
    ifstream fin("bellmanford.in");
    ofstream fout("bellmanford.out");

    fin >> N >> M;
    for (int i = 1, nod1, nod2, cost; i <= M; ++i)
    {
        fin >> nod1 >> nod2 >> cost;
        V[nod1].push_back(make_pair(nod2, cost));
    }

    for (int i = 1; i <= N; ++i)
        D[i] = INF;
    D[1] = 0;

    Q.push(1);
    inqueue[1] = true;

    bool ok = true;
    while (!Q.empty() && ok)
    {
        int now = Q.front();
        inqueue[now] = false;

        for (vector<pair<int, int> >::iterator it = V[now].begin(); it != V[now].end(); ++it)
            if (D[now] + it->second < D[it->first])
            {
                D[it->first] = D[now] + it->second;
                ++times[it->first];

                if (times[it->first] >= N)
                {
                    ok = false;
                    break;
                }
                if (!inqueue[it->first])
                {
                    Q.push(it->first);
                    inqueue[it->first] = true;
                }
            }

        Q.pop();
    }

    if (!ok) fout << "Ciclu negativ!\n";
    else
    {
        for (int i = 2; i <= N; ++i)
            fout << D[i] << ' ';
        fout << '\n';
    }

    fin.close();
    fout.close();
}