Cod sursa(job #552879)

Utilizator marcelcodreaCodrea Marcel marcelcodrea Data 13 martie 2011 01:15:36
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <stdio.h>
#include <queue>
#include <algorithm>

#define N 50005
#define M 250005
#define INF 50000005
using namespace std;


struct Nod {
    int v;
    int cost;
    Nod* next;
};
Nod* lv[N];
int n,m;
int d[N];
int isIn[N];
int cnt[N];
queue<int> Q;
void Insert(Nod *&c, int val, int cos) {
    Nod* nou = new Nod();
    nou -> v = val;
    nou -> cost = cos;
    nou -> next = c;
    c = nou;
}
int main()
{
    freopen("bellmanford.in","r",stdin);
    freopen("bellmanford.out","w",stdout);

    scanf("%d %d",&n,&m);
    for(int i = 1; i <= m; i++) {
        int x, y, cost;
        scanf("%d %d %d",&x,&y,&cost);
        Insert(lv[x], y, cost);
    }
    for(int i = 2; i <= n; i++) {
     d[i] = INF;
     isIn[i] = 0;
    }
    isIn[1] = 1;
    Q.push(1);
    int negativ = 0;
    while (Q.size() != 0 && !negativ) {
     isIn[Q.front()] = 0;
     int aux = Q.front();
     Q.pop();
     for(Nod* it = lv[aux]; it != 0; it = it -> next)
      if (d[it -> v] > d[aux] + it -> cost) {
       d[it -> v] = d[aux] + it -> cost;
       if (cnt[it->v] >= n) {
               negativ = 1;
           }
       if (isIn[it->v] == 0) {
           Q.push(it->v);
           cnt[it->v]++;
           isIn[it->v] = 1;
       }
      }
    }
    if (negativ == 1) printf("Ciclu negativ!\n");
    else {
      for(int i = 2; i <= n; i++)
        printf("%d ",d[i]);
    }

    return 0;
}