Cod sursa(job #1205666)

Utilizator gabib97Gabriel Boroghina gabib97 Data 7 iulie 2014 16:59:57
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 2.45 kb
#include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <vector>
#include <ctype.h>
#define inf 1000000000
using namespace std;
int i,n,m,*d,lg,j,k,sw,*arcx,*arcy,*arcc,*f;
long long nr;
char *F;
bool o[50005];
vector< pair<int,int> > G[50005];
queue<int> Q;
void init()
{
    int x,y,c;
    fseek(stdin,0,SEEK_END);
    lg=ftell(stdin);
    rewind(stdin);
    F=(char*) calloc(lg+1,sizeof(char));
    fread(F,sizeof(char),lg,stdin);
    for (i=0;isdigit(F[i]);i++) n=n*10+F[i]-'0';
    j=i+1;
    for (i=j;isdigit(F[i]);i++) m=m*10+F[i]-'0';
    arcx=(int*) calloc(m+1,sizeof(int));
    arcy=(int*) calloc(m+1,sizeof(int));
    arcc=(int*) calloc(m+1,sizeof(int));
    for (k=1;k<=m;k++)
    {
        x=y=c=0;
        j=i+1; sw=0;
        if (F[j]=='-') {sw=1; j++;}
        for (i=j;isdigit(F[i]);i++) x=x*10+F[i]-'0';
        if (sw) x*=-1;
        j=i+1; sw=0;
        if (F[j]=='-') {sw=1; j++;}
        for (i=j;isdigit(F[i]);i++) y=y*10+F[i]-'0';
        if (sw) y*=-1;
        j=i+1; sw=0;
        if (F[j]=='-') {sw=1; j++;}
        for (i=j;isdigit(F[i]);i++) c=c*10+F[i]-'0';
        if (sw) c*=-1;
        G[x].push_back(make_pair(y,c));
        arcx[k]=x; arcy[k]=y; arcc[k]=c;
    }
    free(F);
    d=(int*) calloc(n+1,sizeof(int));
    f=(int*) calloc(n+1,sizeof(int));
    for (i=1;i<=n;i++) d[i]=inf;
}
void bellmanford(int s)
{
    int i,x,y,c,z;
    Q.push(s); d[s]=0;
    while(!Q.empty())
    {
        x = Q.front();
        Q.pop();
        o[x]=0;
        z = G[x].size();
        for(i=0;i<z;i++)
        {
            y = G[x][i].first;
            c = G[x][i].second;
            if(d[y] > d[x] + c)
            {
                d[y] = d[x] + c;
                if (!o[y])
                {
                    if (f[y]>n) {printf("Ciclu negativ"); exit(0);}
                    else
                    {
                        Q.push(y);
                        o[y]=1;
                    }
                }

            }
        }
    }
}
bool verif_negativ()
{
    int i;
    for (i=1;i<=m;i++)
        if (d[arcy[i]]>d[arcx[i]]+arcc[i]) return true;
    return false;
}
int main()
{
    freopen ("bellmanford.in","r",stdin);
    freopen ("bellmanford.out","w",stdout);
    init();
    bellmanford(1);
    if (verif_negativ()) printf("Ciclu negativ!");
    else
        for (i=2;i<=n;i++) printf("%i ",d[i]);
    fclose(stdin);
    fclose(stdout);
    return 0;
}