Cod sursa(job #1988754)

Utilizator Emy1337Micu Emerson Emy1337 Data 4 iunie 2017 16:03:57
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

const int maxN = 5e4+5;
vector<pair<int,int>> g[maxN];

int dist[maxN];

int main()
{
    int n, m;
    fin >> n >> m;
    while(m--)
    {
        int x, y, z;
        fin >> x >> y >> z;
        g[x].push_back({y,z});
    }

    for(int i =1; i<=n; i++)
        dist[i] = INT_MAX;

    dist[1] = 0;

    for(int k=1; k<=n; k++)
    {
        for(int i=1; i<=n; i++)
        {
            if(dist[i] != INT_MAX)
            {
                for(auto it: g[i])
                    if(dist[i] + it.second < dist[it.first])
                        dist[it.first] = dist[i] + it.second;
            }
        }
    }

    for(int i=1; i<=n; i++)
    {
        if(dist[i] != INT_MAX)
        {
            for(auto it: g[i])
                if(dist[i] + it.second < dist[it.first])
                {
                    fout << "Ciclu negativ!\n";
                    return 0;
                }
        }
    }



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


    return 0;

}