Cod sursa(job #1226455)

Utilizator gabib97Gabriel Boroghina gabib97 Data 5 septembrie 2014 15:15:04
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.1 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,*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';
    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));
    }
    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;
                        f[y]++;
                    }
                }
            }
        }
    }
}
int main()
{
    freopen ("bellmanford.in","r",stdin);
    freopen ("bellmanford.out","w",stdout);
    init();
    bellmanford(1);
    for (i=2;i<=n;i++) printf("%i ",d[i]);
    fclose(stdin);
    fclose(stdout);
    return 0;
}