Cod sursa(job #2215894)

Utilizator TheNextGenerationAyy LMAO TheNextGeneration Data 24 iunie 2018 09:48:02
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>

using namespace std;

ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int INF = 1<<30;
int dist[50005];
int viz[50005];
vector < pair<int,int> > v[50005];

int main()
{
    int n,m;
    in >> n >> m;
    for (int i = 1; i<=m; i++)
    {
        int x,y,val;
        in >> x >> y >> val;
        v[x].push_back({y,val});
    }
    for (int i = 2; i<=n; i++)
        dist[i] = INF;
    queue<int> q;
    q.push(1);
    bool negative = 0;
    while (!q.empty() && !negative)
    {
        int now = q.front();
        q.pop();
        viz[now]++;
        if (viz[now]>n)
        {
            negative = 1;
            break;
        }
        for (auto it: v[now])
        {
            if (dist[it.first]>dist[now]+it.second)
            {
                dist[it.first] = dist[now]+it.second;
                q.push(it.first);
            }
        }
    }
    if (negative)
        out << "Ciclu negativ!";
    else
        for (int i = 2; i<=n; i++)
            out << dist[i] << " ";
}