CSES - Pizzeria Queries
Author: Dong Liu
Time Complexity:
When we query the minimum cost to buy a pizza at point , we can split it into two cases ()
- going downwards (): the cost would be
- going upwards (): the cost would be
Since and are constant, we can first calculate the best cost and then add for the downwards cost and for the upwards cost.
Thus, if we keep two min segtrees (one for going downwards and one for going upwards), we can keep track of the minimum cost by setting each value in the downwards segtree to and each value in the upwards segtree to .
To query, we can simulate going downwards or upwards from position . To go downwards, we must buy pizza in the range so we query the minimum cost in the range . Going upwards is similar to going downwards, but instead of buying pizza in the range , we're buying pizza in the range ; thus we query the range in the upwards segtree.
C++
#include <bits/stdc++.h>using namespace std;template <class T> struct SegTree {T U = 1e9;T F(T a, T b) { return min(a, b); }int N;vector<T> t;SegTree() {}SegTree(int N) : N(N), t(4 * N, U) {}
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!