Cod sursa(job #1124073)

Utilizator andreea_alexandraAndreea Alexandra andreea_alexandra Data 26 februarie 2014 11:13:34
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <cstdio>
#include<vector>
#include<queue>
#define MAX_N 50002
#define inf 250000000
using namespace std;
queue<int> q;
int N, M, dist[MAX_N], contor[MAX_N];
bool isinqueue[MAX_N];
vector<pair <int, int> > graph[MAX_N];
FILE *f, *g;
int main()
{
    int ok=1;

    f = fopen("bellmanford.in", "r");
    g = fopen("bellmanford.out", "w");

    fscanf(f, "%d%d", &N, &M);
    for(int i=0; i<M; i++)
    {
        int x, y, c;
        fscanf(f, "%d%d%d", &x, &y, &c);
        graph[x].push_back(make_pair(y, c));
    }

    q.push(1);
    isinqueue[1]=true;
    for(int i=2; i<=N; i++)
        dist[i]=inf;
    dist[1]=0;
    while(!q.empty() && ok)
    {
        int x=q.front();
        isinqueue[x]=false;
        q.pop();
        for(int i=0; i<graph[x].size(); i++)
        {
            int vecin=graph[x][i].first;
            int cost=graph[x][i].second;
            if(dist[vecin]>dist[x]+cost)
            {
                dist[vecin]=dist[x]+cost;
                if(isinqueue[vecin]==false)
                {
                    isinqueue[vecin]=true;
                    q.push(vecin);
                }
                contor[vecin]++;
            }
            if(contor[vecin]==N)
                ok=0;
        }
    }

    if(ok==0)
        fprintf(g, "Ciclu negativ!");
    else
        for(int i=2; i<=N; i++)
            fprintf(g, "%d ", dist[i]);
    fclose(f);
    fclose(g);
    return 0;
}