Submission #1318967

#TimeUsernameProblemLanguageResultExecution timeMemory
1318967vaishakhvSafety (NOI18_safety)C++20
4 / 100
2095 ms7400 KiB
// Source: https://usaco.guide/general/io

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define eb emplace_back // faster than push_back xD

// pbds UwU
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
#define oset tree<pair<ll,ll>, null_type,less<pair<ll,ll>>, rb_tree_tag,tree_order_statistics_node_update> // using ms :)) 

// my io library :D
#define m1(x) template<class T, class... U> void x(T&& a, U&&... b)
#define m2(x) (ll[]){(x forward<U>(b),0)...}

m1(pr){cout << forward<T>(a);  m2(cout << " " <<); cout << "\n";}
m1(re){cin >> forward<T>(a); m2(cin >>);}

ll n, h;
vector<ll> s;
ll best = 1e18;

void backtrack(ll i, ll prev, ll cost){
    if(i == n){
        best = min(best, cost);
        return;
    }
    for(ll j = max(0LL, prev - h); j <= prev + h; j++){
        backtrack(i+1, j, cost + abs(s[i]-j));
    }
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    re(n, h);
    s.resize(n);
    for(ll i{}; i < n; i++) re(s[i]);

    // BRUTE-FORCE SUBTASK 3 :D
    for(ll i{}; i <= s[0] + n*h; i++){
        backtrack(1, i, abs(s[0]-i));
    }
    pr(best);

    /*
    // older dp
    ll maxl = *max_element(s.begin(), s.end());
    vector<vector<ll>> dp(n, vector<ll>(maxl+1, 1e18));

    for (ll i{}; i <= maxl; i++){
        dp[0][i] = abs(s[0]-i);
    }

    for (ll i = 1; i < n; i++) {
        oset t;
        for (ll k{}; k <= min(maxl, h); k++) {
            t.insert({dp[i-1][k], k});
        }

        for (ll j{}; j <= maxl; j++) {
            ll tempmin = t.begin()->first;
            dp[i][j] = tempmin + abs(j - s[i]);
            ll low = j - h, high = j + h + 1;

            if (low >= 0) {
                t.erase({dp[i-1][low], low});
            }            
            if (high <= maxl) {
                t.insert({dp[i-1][high], high});
            }
        }
    }

    ll ans = *min_element(dp[n-1].begin(), dp[n-1].end());
    pr(ans);
    */
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...