Cod sursa(job #1788890)

Utilizator HuskyezTarnu Cristian Huskyez Data 26 octombrie 2016 16:15:55
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <vector>
#include <cstring>
#include <fstream>
#include <queue>

#define infile "bellmanford.in"
#define outfile "bellmanford.out"

using namespace std;

ifstream in(infile);
ofstream out(outfile);

struct edge{
    int node;
    int cost;
};

int n, m;
int x, y, c;
vector<edge> graph[50005];
int dist[50005];
int trecut[50005];
queue<int> q;
const int inf = 1000000;

bool BFS(int start)
{
    for(int i=1; i<=n; i++) dist[i] = inf;

    dist[start] = 0;

    for(q.push(start); not q.empty(); q.pop()){
        int nod = q.front();
        trecut[nod]++;
        if(trecut[nod] > n){
            out << "Ciclu negativ!" << '\n';
            return true;
        }
        for(vector<edge> :: iterator it=graph[nod].begin(); it!=graph[nod].end(); it++){
            if(dist[it->node] > dist[nod] + it->cost){
                dist[it->node] = dist[nod] + it->cost;
                q.push(it->node);
            }
        }
    }
    return false;
}


int main()
{

    in >> n >> m;
    for(int i=0; i<m; i++){
        in >> x >> y >> c;
        graph[x].push_back({y, c});
    }

    if(BFS(1)){
        return 0;
    }else{
        for(int i=2; i<=n; i++){
            out << dist[i] << ' ';
        }
    }

    return 0;
}