Cod sursa(job #1988693)

Utilizator Horia14Horia Banciu Horia14 Data 4 iunie 2017 12:01:26
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include<cstdio>
#include<queue>
#define MAX_N 50000
#define oo 0x7fffffff
using namespace std;

struct nod
{
    int val, cost;
    nod* next;
};

nod* L[MAX_N+1];

int ItNod[MAX_N+1], d[MAX_N+1], n, m;
bool used[MAX_N+1], ok;
queue<int>Q;

inline void Insert(int x, int y, int c)
{
    nod* elem = new nod;
    elem->val = y;
    elem->cost = c;
    elem->next = L[x];
    L[x] = elem;
}

void BellmanFord(int x)
{
    int i, Nod;
    nod* p;
    for(i=1; i<=n; i++)
        d[i] = oo;
    d[x] = 0;
    Q.push(x);
    used[x] = true;
    while(!Q.empty() && !ok)
    {
        Nod = Q.front();
        Q.pop();
        used[Nod] = false;
        p = L[Nod];
        while(p != NULL)
        {
            if(d[p->val] > d[Nod] + p->cost)
            {
                d[p->val] = d[Nod] + p->cost;
                if(!used[p->val])
                {
                    Q.push(p->val);
                    used[p->val] = true;
                    if(++ItNod[p->val] > n)
                        ok = true;
                }
            }
            p = p->next;
        }
    }
}

int main()
{
    int i, a, b, c;
    FILE *fin, *fout;
    fin = fopen("bellmanford.in","r");
    fout = fopen("bellmanford.out","w");
    fscanf(fin,"%d%d",&n,&m);
    for(i=1; i<=m; i++)
    {
        fscanf(fin,"%d%d%d",&a,&b,&c);
        Insert(a,b,c);
    }
    fclose(fin);
    BellmanFord(1);
    if(ok)
        fprintf(fout,"Ciclu negativ!\n");
    else
    {
        for(i=2; i<=n; i++)
            fprintf(fout,"%d ",d[i]);
        fprintf(fout,"\n");
    }
    fclose(fout);
    return 0;
}