Cod sursa(job #1337731)

Utilizator TeodorPPaius Teodor TeodorP Data 9 februarie 2015 13:55:50
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <vector>
#include <queue>


using namespace std;
ifstream is("bellmanford.in");
ofstream os("bellmanford.out");

int n, m;
vector<vector<pair<int,int> >  > G;
queue<int> q;
bool inq[50001];
int aux1, aux2, aux3;
int d[50001];
int cnt[50001];

void BellmanFord();



int main()
{
    is >> n >> m;
    G.resize(n+1);

    for(int i = 1; i <= n; ++i)
        d[i] = 0x3f3f3f3f;
    d[1] = 0;
    q.push(1);
    inq[1] = true;


    for(int i = 1; i <= m; ++i)
    {
        is >> aux1 >> aux2 >> aux3;
        G[aux1].push_back(make_pair(aux2, aux3));
    }

    BellmanFord();

    for(int i = 2; i <= n; ++i)
    {
        os << d[i] << ' ';
    }
    is.close();
    os.close();
    return 0;
}

void BellmanFord()
{
    int x;
    int vec;
    int cost;
    while(!q.empty())
    {
        x = q.front();
        q.pop();
        inq[x] = 0;
        for(const auto& i : G[x])
        {
            vec = i.first;
            cost = i.second;
            if(d[vec] > d[x] + cost)
            {
                d[vec] = d[x] + cost;
                if(!inq[vec])
                {
                    cnt[vec]++;
                    if(cnt[vec] == n)
                    {
                        os << "Ciclu negativ!";
                        return;
                    }
                    q.push(vec);
                    inq[vec] = true;
                }
            }
        }
    }

}