Cod sursa(job #2690728)

Utilizator SochuDarabaneanu Liviu Eugen Sochu Data 25 decembrie 2020 14:40:46
Problema Algoritmul Bellman-Ford Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.38 kb
#include <bits/stdc++.h>
//#pragma GCC optimize ("03")
#define FastIO ios_base::sync_with_stdio(false) , cin.tie(0) , cout.tie(0)
#define FILES freopen("bellmanford.in" , "r" , stdin) , freopen("bellmanford.out" , "w" , stdout)
#define ll long long
#define ull unsigned long long
#define ld long double
#define eb emplace_back
#define pb push_back
#define qwerty1 first
#define qwerty2 second
#define qwerty3 -> first
#define qwerty4 -> second
#define umap unordered_map
#define uset unordered_set
#define pii pair < int , int >
#define pq priority_queue
#define dbg(x) cerr << #x << ": " << x << '\n'

namespace FastRead
{
    char buff[5000];int lg = 0 , p = 0;
    char nc()
    {
        if(lg == p){lg = fread(buff , 1 , 5000 , stdin);p = 0;if(!lg) return EOF;}
        return buff[p++];
    }
    template<class T>void read(T&x)
    {
        T sgn = 1; char c;while(!isdigit(c = nc()))if(c == '-')sgn = -1;
        x = c - '0';while(isdigit(c = nc()))x = x * 10 + c - '0';x *= sgn;
    }
}

using namespace FastRead;
using namespace std;

const int N = 25e4 + 10;
const int M = 5e4 + 10;
const ld PI = acos(-1);
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

int n , m;
int cost[M];
multiset < pii > d;
vector < int > a[M];

struct edge
{
    int x , y , c;
}e[N];

void bellman()
{
    int i;

    for(i = 2 ; i <= n ; i++)
        cost[i] = INT_MAX;

    cost[1] = 0;
    d.insert({0 , 1});

    ll cnt = 0;

    while(!d.empty() && cnt <= 1ll * n * m)
    {
        ++cnt;
        int nod = d.begin() -> second;
        int dist = d.begin() -> first;
        d.erase(d.begin());

        for(auto i : a[nod])
        {
            int go = e[i].y;
            int c = e[i].c;

            if(dist + c < cost[go])
                cost[go] = dist + c , d.insert({cost[go] , go});
        }
    }
}

bool inline neg()
{
    for(int i = 1 ; i <= m ; i++)
        if(cost[ e[i].x ] + e[i].c < cost[ e[i].y ])
            return 1;

    return 0;
}

signed main()
{
	#ifndef ONLINE_JUDGE
		FastIO , FILES;
	#endif

    int i;

    cin >> n >> m;

    for(i = 1 ; i <= m ; i++)
    {
        cin >> e[i].x >> e[i].y >> e[i].c;
        a[ e[i].x ].pb(i);
    }

    bellman();

    if(neg()) cout << "Ciclu negativ!";
    else for(i = 2 ; i <= n ; i++)
        cout << cost[i] << ' ';

    return 0;
}