Cod sursa(job #3194466)

Utilizator matei__bBenchea Matei matei__b Data 18 ianuarie 2024 09:26:44
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ld long double
#define chad char
#define mod 1000000007
#define dim 100005
#define lim 1000000
#define mdim 1501
#define mult 2e9
#define maxx 200002
#define simaimult 1e17
#define FOR(i,a,b) for(int i=(a); i<=(b); i++)
#define pli pair<ll,int>
#define pil pair<int,ll>
#define piii pair<int,pair<int,int> >
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pb push_back
#define mp make_pair
#define nr_biti __builtin_popcount
using namespace std;

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

int n,m;

vector<pii> g[dim];
int dist[dim];
int fq[dim];

int main()
{
    ios_base::sync_with_stdio(false);
    fin.tie(nullptr);
    fout.tie(nullptr);

    fin >> n >> m;

    for(int i=1; i<=m; i++)
    {
        int x,y,cost;

        fin >> x >> y >> cost;

        g[x].pb(mp(y,cost));

        //cout << x << " " << y << " " << cost << "\n";
    }

    queue<int> q;

    bool neg=0;

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

    dist[1]=0;
    q.push(1);

    while(q.size())
    {
        if(neg)
            break;

        int nod=q.front();
        q.pop();

        //cout << nod << "\n";

        for(auto it:g[nod])
        {
            int vec=it.first;
            int cost=it.second;

            if(dist[vec]>dist[nod]+cost)
            {
                dist[vec]=dist[nod]+cost;
                q.push(vec);

                fq[vec]++;

                if(fq[vec]==n)
                    neg=1;
            }
        }
    }


    if(neg)
    {
        fout << "Ciclu negativ!";
        return 0;
    }

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

    return 0;
}