Cod sursa(job #1917563)

Utilizator MailatMailat Radu Mailat Data 9 martie 2017 12:32:06
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdtr1c++.h>
#define INF numeric_limits <int> ::max()
#define maxn 50001
using namespace std;

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

vector < pair <int, int> > A[maxn];
set <pair <int, int> > h;
vector <pair <int, int> > ::iterator it;
vector <int> D;
int N, M, x0 = 1;

int bellmanford(int S) {
    int node, to, cost;
    for(int i=1; i <= N-1; i++) {
        for(int j=1; j<=N; j++) {
            for(it = A[j].begin(); it != A[j].end(); ++it) {
                if(D[j] == INF) {
                    ++it;
                    continue;
                }
                to = it->first;
                cost = it->second;
                if(D[to] > D[j] + cost) {
                    D[to] = D[j] + cost;
                }
            }
        }
    }
    for(int i=1; i<=N; i++) {
        for(it = A[i].begin(); it!=A[i].end(); ++it) {
            to = it->first;
            cost = it->second;
            if(D[to] > D[i] + cost) return i;
        }
    }
    return -1;
}

void init() {
    int x, y, c;
    fin >> N >> M;
    for(int i=0;i < M; i++) {
        fin >> x >> y >> c;
        A[x].push_back(make_pair(y,c));
    }
    for(int i=0; i <=N; i++) D.push_back(INF);
    D[x0] = 0;
    if(bellmanford(x0) == -1) {
        for(int i=2; i<=N; i++) fout << D[i] << " ";
    }
    else {
        fout << "Ciclu negativ!";
    }
}

int main()
{
    init();
    return 0;
}