Cod sursa(job #1646699)

Utilizator redducks100Andronache Simone redducks100 Data 10 martie 2016 17:17:37
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <bits/stdc++.h>

using namespace std;

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

#define INF INT_MAX

const int NMAX = 50001;
vector< pair<int,int> > adjList[NMAX];
int dist[NMAX];
int cantEdge[NMAX];
int used[NMAX];
queue<int> q;

bool isNegative;

void BellmanFord(int source,int n)
{
    for(int i=0; i<=n; i++)
    {
        dist[i] = INF;
        cantEdge[i]  = 0;
    }

    q.push(source);
    dist[source] = 0;
    while(!q.empty() && !isNegative)
    {
        int curNode = q.front();
        q.pop();
        used[curNode] = false;

        for(int i=0; i<adjList[curNode].size(); i++)
        {
            if(adjList[curNode][i].second + dist[curNode] < dist[adjList[curNode][i].first])
            {
                dist[adjList[curNode][i].first] = adjList[curNode][i].second + dist[curNode];

                if(!used[adjList[curNode][i].first])
                {
                    if(cantEdge[adjList[curNode][i].first] > n)
                    {
                        isNegative = true;
                    }
                    else
                    {
                        q.push(adjList[curNode][i].first);
                        used[adjList[curNode][i].first] = true;
                        cantEdge[adjList[curNode][i].first] ++;
                    }
                }
            }
        }
    }
}


int main()
{
    int n,m,x,y,cost;
    f>>n>>m;
    for(int i=0; i<m; i++)
    {
        f>>x>>y>>cost;
        adjList[x].push_back(make_pair(y,cost));
    }
    isNegative = false;
    BellmanFord(1,n);
    if(isNegative)
    {
        g<<"Ciclu negativ!";
    }
    else
    {
        for(int i=2; i<=n; i++)
            g<<dist[i]<<" ";
    }
    return 0;
}