Cod sursa(job #2022732)

Utilizator MaligMamaliga cu smantana Malig Data 17 septembrie 2017 08:51:58
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>
#include <vector>

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

#define ll long long
#define ull unsigned long long
#define ui unsigned int
#define pb push_back
#define mp make_pair
const int NMax = 5e4 + 5;
const int inf = 1e9 + 5;
const int mod = 100003;
using zint = int;

int N,M;
int dist[NMax];
vector< pair<int,int> > v[NMax];

int main() {
    in>>N>>M;
    for (int i=1;i <= M;++i) {
        int x,y,c;
        in>>x>>y>>c;

        v[x].pb( mp(y,c) );
        //v[y].pb( mp(x,c) );
    }

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

    bool update = false;
    for (int c=1;c <= N;++c) {
        update = false;
        for (int i=1;i <= N;++i) {
            for (auto p : v[i]) {
                int nxt = p.first, cost = p.second;
                if (dist[nxt] > dist[i] + cost) {
                    dist[nxt] = dist[i] + cost;
                    update = true;
                }
            }
        }
    }

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

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