Cod sursa(job #1831953)

Utilizator NinjaCubeMihai Radovici NinjaCube Data 19 decembrie 2016 10:09:58
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <bitset>
#define inf 10000000

using namespace std;

int n,m,c,dist[50050],viz[50050];

vector <pair <int,int > > v[50050];

queue < int > q;

void read()
{
    int x,y,c;
    scanf("%d%d",&n,&m);

    for (int i=2; i<=n; ++i)
        dist[i]=inf;

    q.push(1);

    for(int i=1; i<=m; i++)
    {
        scanf("%d%d%d",&x,&y,&c);
        v[x].push_back(make_pair(y,c));
    }

    dist[1]=0;

}

void bell()
{
    while(!q.empty())
    {
        int b=q.front();
              q.pop();

        for(vector <pair<int,int > > :: iterator it=v[b].begin(); it!=v[b].end(); ++it)
        {
            if(dist[b]+it->second < dist[it->first])
            {
                dist[it->first]=dist[b]+it->second;
                viz[it->first]++;

                if(viz[it->first] > n)
                {
                    printf("Ciclu negativ!");
                    return;
                }
                q.push(it->first);
            }
        }
    }
    for (int i=2; i<=n; ++i)
        printf("%d ",dist[i]);
}


int main()
{
    freopen("bellmanford.in","r",stdin);
    freopen("bellmanford.out","w",stdout);
    read();
    bell();
    return 0;
}