Cod sursa(job #1296997)

Utilizator Vele_GeorgeVele George Vele_George Data 21 decembrie 2014 17:04:22
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#define inf (1<<30)
using namespace std;

fstream f("bellmanford.in");
fstream go("bellmanford.out");

struct perechi{

    int nod,cost;

}aux;
int x,y,c,n,m;
vector< vector<perechi> > g;
vector<bool> inq;
vector<int> used,dist;
queue<int> q;


bool bellman(int x)
{
    q.push(x);
    dist[x]=0;
    used[x]=1;
    inq[x]=true;
    while (!q.empty())
    {
        x=q.front();
        q.pop();
        inq[x]=false;
        for(int i=0; i<g[x].size(); i++)
        {

            int y=g[x][i].nod;
            int c=g[x][i].cost;
            if (dist[y]>dist[x]+c)
            {

                dist[y]=dist[x]+c;

                if (!inq[y])
                {
                    q.push(y);
                    inq[y]=true;
                }
                used[y]++;
                if (used[y]>=n) return false;



            }

        }



    }

    return true;



}

int main()
{

    f>>n>>m;
    g.resize(n+1);
    for(int i=0; i<=n; i++){

        used.push_back(0);
        inq.push_back(false);
        dist.push_back(inf);

    }

     for(int i=1; i<=m; i++)
    {
        f>>x>>y>>c;
        aux.nod=y;
        aux.cost=c;
        g[x].push_back(aux);
    }

    //if (bellman(1)) for(int i=2; i<=n; i++) go<<dist[i]<<" ";
    //else go<<"Ciclu negativ!";


    f.close();
    go.close();


    return 0;
}