Cod sursa(job #1337721)

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


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

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

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(aux2);
        c[aux1][aux2] = aux3;
    }

    BellmanFord();

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

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

}