Cod sursa(job #989860)

Utilizator gunner_292Mihai Manolescu gunner_292 Data 26 august 2013 17:12:49
Problema Algoritmul Bellman-Ford Scor 85
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include<fstream>
#include<vector>
#include<queue>

#define dmax 50003

using namespace std;

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

int n,m;

struct edge
{
    int vertex;
    int weight;
};

vector<edge> adj[dmax];

queue<int> q;

int count[dmax];



void bellmanford()
{
    int minD[dmax];
    bool negC = false;

    for(int i=2; i<=n; i++)
        minD[i] = -1;

    q.push(1);
    minD[1] = 0;
    count[1] = 1;

    while(!q.empty() && negC == false)
    {
        int currentV = q.front();
        q.pop();

        vector<edge>::iterator it;

        for(it = adj[currentV].begin(); it < adj[currentV].end(); it++)
        {
            if(minD[it->vertex] == -1 || minD[it->vertex] > minD[currentV] + it->weight)
            {
                minD[it->vertex] = minD[currentV] + it->weight;
                q.push(it->vertex);
                count[it->vertex]++;

                if(count[it->vertex] == n)
                {
                    out<<"Ciclu negativ!";
                    negC = true;
                }
            }
        }
    }

    if(negC == false)
        for(int i=2; i <= n; i++)
            out<<minD[i]<<" ";

}




int main()
{
    in>>n>>m;

    for(int i=1; i<=m; i++)
    {
        int v1, v2, w;

        in>>v1>>v2>>w;

        edge e;

        e.weight = w;
        e.vertex = v2;
        adj[v1].push_back(e);
    }

    in.close();

    bellmanford();

    out.close();

    return 0;
}