Cod sursa(job #1922785)

Utilizator Kln1000Ciobanu Bogdan Kln1000 Data 10 martie 2017 18:54:59
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <bitset>
#include <queue>
#include <vector>
#include <cstring>
#include <iostream>

#define INF 0x7FFFFFFF

using namespace std;

ifstream f ("bellmanford.in");
ofstream t ("bellmanford.out");

struct edge{
    int to,cost;
};

bool cycle=false;
int n,m;
vector <edge> v[50010];
vector <int> dist(50010,INF),counter(50010);

void bellmanford(int nod){
    dist[nod]=0;
    queue <int> q;
    bitset <50010> in_queue;
    q.push(nod);
    in_queue[nod]=true;
    while (!q.empty() and cycle==false){
        int current=q.front();
        q.pop();
        in_queue[current]=false;
        for (auto i:v[current])
            if (dist[i.to]>dist[current]+i.cost){
                dist[i.to]=dist[current]+i.cost;
                if (!in_queue[i.to])
                    if (counter[i.to]>n)
                        cycle=true;
                    else{
                        ++counter[i.to];
                        q.push(i.to);
                        in_queue[i.to]=true;
                    }
            }
    }
}

int main(){
    f>>n>>m;
    for (int x,y,c,i=0;i<m;++i)
        f>>x>>y>>c,
        v[x].push_back({y,c});
    bellmanford(1);
    if (cycle)
        t<<"Ciclu negativ!";
    else
        for (int i=2;i<=n;++i)
            t<<dist[i]<<" ";
    return 0;
}