Cod sursa(job #1708037)

Utilizator TimoteiCopaciu Timotei Timotei Data 26 mai 2016 13:56:15
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>
#include <iostream>
#include <queue>
#include <vector>
#include <bitset>
#define INF 1<<30
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

int n, m, costMin[50005], y1, y2, node, new_node, pas;
struct element{
  int vecin, cost;
}x;
vector <element> v[50005];
queue <int> C;
bitset <50005> is_in_tail;
void read(){
 f >> n >> m;
 for(int i = 1; i <= m; ++i){
    f >> y1 >> y2 >> x.cost;
    x.vecin = y2;
    v[y1].push_back(x);
 }
}
void bfs(int i){
  is_in_tail[i] = 1;
  node = i;
  C.push(node);
  while(!C.empty() && pas <= 1LL * n * m){
    node = C.front();
    pas++;
    for(int i = 0; i < v[node].size(); ++i){
        new_node = v[node][i].vecin;
        if(costMin[node] + v[node][i].cost < costMin[new_node]){
        costMin[new_node] = costMin[node] + v[node][i].cost;
        if(!is_in_tail[new_node]){
        C.push(new_node);
        is_in_tail[new_node] = 1;
        }
      }
    }
   is_in_tail[node] = 0;
   C.pop();
  }
}
int is_negative(){
  for(int i = 1; i <= n; ++i)
    for(int j = 0; j < v[i].size(); ++j)
       if(costMin[v[i][j].vecin] > costMin[i] + v[i][j].cost)
       return 1;
  return 0;
}
void write(){
 if(is_negative())
    g << "Ciclu negativ!";
 else
  for(int i = 2; i <= n; ++i)
     g << costMin[i] << ' ';
}
int main()
{
    read();
    for(int i = 2; i <= n; ++i)
        costMin[i] = INF;
    bfs(1);
    write();
    return 0;
}