Cod sursa(job #1919822)

Utilizator BogdanisarBurcea Bogdan Madalin Bogdanisar Data 9 martie 2017 21:10:55
Problema Algoritmul Bellman-Ford Scor 65
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <iostream>
#include <climits>
#include <fstream>
#include <vector>

using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");

const int NMax = 1e5 + 5;

// bellman-ford clasic

int N,M;
int dist[NMax];
// dist[i] = distanta de la nodul 1 la nodul i

struct muchie {
    int y,c;
    muchie() {
        muchie(1,0);
    }
    muchie(int a,int b) {
        y = a;
        c = b;
    }
};
vector<muchie> v[NMax];
// v - lista de adiacenta

int main() {
    in>>N>>M;
    for (int i=1;i<=M;++i) {
        int x,y,c;
        in>>x>>y>>c;
        muchie e(y,c);
        v[x].push_back(e);
    }

    for (int i=2;i<=N;++i) {
        dist[i] = 1e8;
    }
    dist[1] = 0;

    bool update = true;
    for (int ct=1;ct<=N;++ct) {

        if (!update) {
            break;
        }

        update = false;
        for (int i=1;i<=N;++i) {
            vector<muchie>::iterator it;
            for (it=v[i].begin();it<v[i].end();++it) {
                if (dist[(it->y)] > dist[i] + (it->c)) {
                    dist[(it->y)] = dist[i] + (it->c);
                    update = true;
                }
            }
        }
    }

    if (update) {
        out<<"Ciclu negativ!";
    }
    else {
        for (int i=2;i<=N;++i) {
            out<<dist[i]<<' ';
        }
        return 0;
    }

    in.close();out.close();
    return 0;
}