Cod sursa(job #1110761)

Utilizator thesvcoolmanLucian Bicsi thesvcoolman Data 18 februarie 2014 13:04:42
Problema Algoritmul Bellman-Ford Scor 85
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include<fstream>
#include<vector>
#include<deque>

#define INF 20000000


using namespace std;

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
struct muchie {int val,vec;};

deque<int> q;
vector<muchie> L[50000];
int n,m,i,x,nrviz[50000],cost[50000],start;
muchie y;
bool inq[50000];

int main()
{
    fin>>n>>m;
    for(i=1;i<=m;i++)
    {
        fin>>x;
        fin>>y.vec>>y.val;
        L[x].push_back(y);
    }
    start=1;

    for(i=1;i<start;i++) cost[i]=INF;
    for(i++;i<=n;i++) cost[i]=INF;

    q.push_back(start);
    nrviz[start]++;inq[start]=true;
    int l;

    while(!q.empty())
    {
        for(l=0;l<L[q[0]].size();l++)
            if(cost[L[q[0]][l].vec]>cost[q[0]]+L[q[0]][l].val)
            {
                cost[L[q[0]][l].vec]=cost[q[0]]+L[q[0]][l].val;
                if(!inq[L[q[0]][l].vec])
                {
                    q.push_back(L[q[0]][l].vec);
                    inq[L[q[0]][l].vec]=true;
                    nrviz[L[q[0]][l].vec]++;
                    if(nrviz[L[q[0]][l].vec]>=n)
                        {fout<<"Ciclu negativ!";return 0;}
                }
            }
        inq[q[0]]=false;
        q.pop_front();
    }

    for(i=2;i<=n;i++)
        fout<<cost[i]<<" ";

    return 0;
}