Cod sursa(job #1787534)

Utilizator HuskyezTarnu Cristian Huskyez Data 24 octombrie 2016 19:38:33
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <iostream>
#include <vector>
#include <cstring>
#include <fstream>
#include <queue>

#define inf 1e8
#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 grad[50005];
queue<int> q;

bool BFS(int start)
{
    memset(dist, inf, sizeof(dist));
    dist[start] = 0;
    for(q.push(start); not q.empty(); q.pop()){
        int nod = q.front();
        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);
                grad[it->node]++;
            }
            if(grad[it->] > n-1){
                out << "Ciclu negativ!" << '\n';
                return true;
            }
        }
    }
}


int main()
{

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

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

    return 0;
}