Cod sursa(job #2036040)

Utilizator calinfloreaCalin Florea calinflorea Data 10 octombrie 2017 10:33:39
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m, ok, drum[50006];
int v[50006];
bool viz[50006];
vector<pair<int, int> >L[50006];
queue < int >q;
void Bellmanford()
{
    int i, o, p, j;
    q.push(1);
    while(!q.empty() && !ok)
    {
        i = q.front();
        q.pop();
        for(j = 0; j < L[i].size(); j++)
        {
            p = L[i][j].first;
            o = L[i][j].second;
            if(drum[p] > drum[i] + p)
            {
                drum[p] = drum[i] + o;
                if(!viz[p])
                {
                    if(v[p] > n)
                        ok = 1;
                    else
                    {
                        q.push(p);
                        v[p]++;
                        viz[p] = 1;
                    }
                }
            }

        }
    }

    if(ok == 1)
        fout << "Ciclu negativ!\n";
    else
        for(i = 2; i <= n; i++)
            fout << drum[i] << " ";

}
int main()
{
    int i, x, y, z;
    fin >> n >> m;
    for(i = 1; i <= m; i++)
    {
        fin >> x >> y >> z;

        L[x].push_back({y, z});
    }
    for(i = 1; i <= n; i++)
        drum[i] = (1 << 30);
    viz[1] = 1;
    drum[1] = 0;
    Bellmanford();
    return 0;
}