Submission #478960

#TimeUsernameProblemLanguageResultExecution timeMemory
478960Lam_lai_cuoc_doiPotatoes and fertilizers (LMIO19_bulves)C++17
100 / 100
159 ms14524 KiB
#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;

template <class T>
void read(T &x)
{
    x = 0;
    register int c;
    while ((c = getchar()) && (c > '9' || c < '0'))
        ;
    for (; c >= '0' && c <= '9'; c = getchar())
        x = x * 10 + c - '0';
}

constexpr bool typetest = 0;
constexpr int N = 5e5 + 5;
/*https://usaco.guide/adv/slope-trick/#potatoes--fertilizers*/
/*https://www.youtube.com/watch?v=p8RxN6Y9OOA*/

int n;
ll a[N], b[N];

void Read()
{
    cin >> n;
    for (int i = 1; i <= n; ++i)
    {
        cin >> a[i] >> b[i];
        a[i] = a[i - 1] + a[i] - b[i];
    }
}

void Solve()
{
    ll res(0);

    for (int i = 1; i <= n; ++i)
    {
        if (a[i] < 0)
        { // First, assume that all have to be non-negative
            res += -a[i];
            a[i] = 0;
        }
        if (a[i] > a[n])
        {
            // assume that all are less or  equal to a[n]
            res += a[i] - a[n];
            a[i] = a[n];
        }
    }

    priority_queue<ll> s;

    for (int i = 1; i <= n; ++i)
    {
        s.emplace(a[i]);
        if (i == 1)
            continue;
        ll ontop = s.top();
        if (ontop > a[i])
        {
            res += ontop - a[i];
            s.pop();
            s.emplace(a[i]);
        }
    }

    cout << res;
}

int32_t main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    //freopen("digits.inp", "r", stdin);
    //freopen("digits.out", "w", stdout);
    int t(1);
    if (typetest)
        cin >> t;
    for (int _ = 1; _ <= t; ++_)
    {
        //cout << "Case #" << _ << ":\n";
        Read();
        Solve();
    }
    //cerr << "\nTime elapsed: " << 1000 * clock() / CLOCKS_PER_SEC << "ms\n";
}

Compilation message (stderr)

bulves.cpp: In function 'void read(T&)':
bulves.cpp:12:18: warning: ISO C++17 does not allow 'register' storage class specifier [-Wregister]
   12 |     register int c;
      |                  ^
#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...