Cod sursa(job #2407445)

Utilizator Cezar211Popoveniuc Cezar Cezar211 Data 16 aprilie 2019 21:14:05
Problema Algoritmul Bellman-Ford Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>
#define NM 50005
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
void read();
int n, m, cnt, dist[NM];
bool ok;
vector<pair<int,int>> v[NM];
int main()
{
    read();
    for(int i=2; i<=n; i++)
        dist[i] = INT_MAX;
    ok = 1;
    while(cnt <= n-1 && ok)
    {
        ok = 0;
        ++cnt;
        for(int i=1; i<=n; i++)
            if(dist[i]!=INT_MAX)
            {
                for(auto it : v[i])
                    if(dist[i]+it.first < dist[it.second])
                    {
                        dist[it.second] = dist[i] + it.first;
                        ok = 1;
                    }
            }
    }
    ok = 0;
    for(int i=1; i<=n; i++)
    {
        for(auto it : v[i])
            if(dist[i]+it.first < dist[it.second])
                dist[it.second] = dist[i]+it.first, ok = 1;
    }
    if(ok)
        fout << "Ciclu negativ!";
    else
        for(int i=2; i<=n; i++)
            fout << dist[i] << ' ';
    return 0;
}
void read()
{
    int x, y, c;
    fin >> n >> m;
    for(int i=1; i<=m; i++)
    {
        fin >> x >> y >> c;
        v[x].push_back({c, y});
    }
}