Cod sursa(job #2433170)

Utilizator dacrisan@yahoo.comDaniela Alex [email protected] Data 26 iunie 2019 05:27:29
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
#define NMAX 50001
#define inf 1e9


struct edge{
    int dest,cost;
    bool operator<(const edge&v)const{
    return cost>v.cost;
    }
    edge(int d=0, int c=0)
    {
        this->dest=d; this->cost=c;
    }

}aux;
int f[NMAX];
vector<edge>g[NMAX];
//priority_queue<edge>pq;
queue<edge>pq;
int dist[NMAX];
bool bellmanford(int n){
    aux.cost=0;
    aux.dest=1;
    pq.push(aux);

    while(!pq.empty())
    {
        //int node=pq.top().dest,cost=pq.top().cost;
        int node=pq.front().dest,cost=pq.front().cost;
        //cout<<"nod:"<<node<<" "<<cost<<endl;
        dist[node]=min(cost,dist[node]);
        f[node]++;
        pq.pop();
        if(f[node]<n)
        {

            for(auto y:g[node])
            {
                if(dist[node]+y.cost<=dist[y.dest])
                {

                    aux.dest=y.dest;
                    aux.cost=y.cost+dist[node];
                    //dist[aux.cost]=y.cost+dist[node];
                    pq.push(aux);
                }

            }
        }
        else
        {
            out<<"Ciclu negativ!";
            return 0;
        }
    }

    return 1;
}
int main()
{

     int n,m;
    in>>n>>m;
    int x,y,cost;
    for(int i=1;i<=n;i++)
        dist[i]=inf;
    for(int i=1;i<=m;i++){
        in>>x>>y>>cost;
        aux.cost=cost;
        aux.dest=y;
        g[x].push_back(aux);
    }
    if(bellmanford(n)){
       /*     for(int i=1;i<=n;i++)
        cout<<f[i]<<" ";
    cout<<endl;*/
        for(int i=2;i<=n;i++)
            cout<<dist[i]<<" ";
    }
    return 0;
}