Cod sursa(job #2454080)

Utilizator bogdan2604Bogdan Dumitrescu bogdan2604 Data 7 septembrie 2019 13:06:28
Problema Algoritmul Bellman-Ford Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f

using namespace std;

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

int n,m,i,j,x,y,pret,inc,sf,cost[50001];
vector < tuple <int,int,int> > muchii;
bool ok;

int main()
{
    ios::sync_with_stdio(0);
    f >> n >> m;
    for(i = 0 ; i < m; ++ i)
    {
        f >> x >> y >> pret;
        muchii.push_back(make_tuple(x,y,pret));
    }
    for(i = 1; i <= n; ++ i)
        cost[i] = INF;
    cost[1] = 0;
    for(i = 1; i < n; ++ i)
    {
        ok = 0;
        for(j = 0 ; j < m; ++ j)
        {
            inc = get<0>(muchii[j]);
            sf = get<1>(muchii[j]);
            pret = get<2>(muchii[j]);
            if(cost[inc] != INF && cost[sf] > cost[inc] + pret)
            {
                cost[sf] = cost[inc] + pret;
                ok = 1;
            }
        }
        if(!ok)
            break;
    }
        for(i = 0; i < m; ++ i)
        {
            inc = get<0>(muchii[i]);
            sf = get<1>(muchii[i]);
            pret = get<2>(muchii[i]);
            if(cost[inc] != INF && cost[sf] > cost[inc] + pret)
            {
                g << "Ciclu negativ!";
                return 0;
            }
        }
        for(i = 2; i <= n; ++ i)
            g << cost[i] << ' ';
    }