Cod sursa(job #1731894)

Utilizator stefanchistefan chiper stefanchi Data 20 iulie 2016 12:45:33
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#define N 50050
#include <queue>
#include <stdio.h>
#include <vector>
#define inf 1000000
using namespace std;
vector <pair <int ,int> > drum[N];
queue <pair <int , int> > q;
int n ,m;
int viz[N];
int distanta[N];


void read()
{
    freopen("bellmanford.in","r",stdin);
    freopen("bellmanford.out","w",stdout);
    scanf("%d %d",&n,&m);
    int a,b,c;
    for(int i  = 2 ; i <= n ; i++)
        distanta[i] = inf;
    for(int i = 1 ; i  <= m ; i++)
    {
        scanf("%d %d",&a,&b,&c);
        drum[a].push_back(make_pair(b,c));
    }
}

void bellmanford()
{
    q.push(make_pair(0,1));

    while(!q.empty())
    {
        int cost = q.front().first;
        int b = q.front().second;
        q.pop();
        for(vector <pair <int , int > > :: iterator it = drum[b].begin() ; it != drum[b].end() ; ++it)
        {
            if(cost+it->second < dist[it->first])
            {
                distanta[it->first]= cost + it->second;
                viz[it->first]++;
                if(viz[it->first] > n)
                {
                    printf("Ciclu negativ!");
                    return;
                }
                q.push(make_pair(distanta[it->first], it->first));
            }
        }
    }
    for(int i = 2; i  <= n ; i++)
        printf("%d ",distanta[i]);
}


int main()
{
    read();
    bellmanford();
    return 0;
}