PrevNext
Not Frequent
 0/10

Convex Hull Trick

Author: Andi Qu

A way to find the maximum or minimum value of several convex functions at given points.

Convex Hull Trick (CHT) problems are usually of the following form:

Given several convex functions fi(x)f_i(x) such that any two functions intersect at most once, answer QQ queries of the form "what is the maximum/minimum fi(x)f_i(x) for some given xx?".

This section is not complete.

Feel free to file a request to complete this using the "Contact Us" button.

Ben - be clearer about what conditions need to be satisfied

Examples of such functions include:

  • The straight line (y=mx+cy = mx + c)
  • The square-root function (y=xa+by = \sqrt{x - a} + b)

There are several data structures one can use to solve these problems efficiently.

In this module, we'll focus on the special case of CHT where "slopes" of functions are monotonic. This specific case is solvable in O(N)O(N) using a std::deque in C++. For the more general O(NlogN)O(N \log N) CHT, see the LineContainer module.

Focus Problem – read through this problem before continuing!

Tutorial

Solution - The Fair Nut and Rectangles

I won't analyse this problem in great detail since the Codeforces blog in the resources already does so, but essentially, we sort the rectangles by xx-coordinate and get the following DP recurrence:

dp[i]=piqiai+maxj<i(pjqi+dp[j])dp[i] = p_i \cdot q_i - a_i + \max_{j < i}(-p_j \cdot q_i + dp[j])

Notice how the pjqi+dp[j]-p_j \cdot q_i + dp[j] part of the recurrence describes a straight line y=mx+cy = mx + c.

Since we sorted the rectangles and no two rectangles are nested, the slopes of the lines we insert are strictly increasing. The query positions are also strictly increasing.

This means we can solve this problem using CHT in O(N)O(N) time! Here is my implementation:

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
struct Rect {
ll x, y, a;
bool operator<(Rect B) { return x < B.x; }
};
Rect a[1000001];

Problems

StatusSourceProblem NameDifficultyTagsSolution
APIOEasy
Show Tags

DP, convex

External Sol
CEOIEasy
Show Tags

DP, convex

View Solution
IOIEasy
Show Tags

DP, convex

External Sol
POINormal
Show Tags

DP, convex

View Solution
APIONormal
Show Tags

DP, convex

POIHard
Show Tags

DP, convex

View Solution
PlatHard
Show Tags

DP, convex

External Sol
PlatHard
Show Tags

convex

External Sol
JOIHard
Show Tags

DP, convex

View Solution

Give Us Feedback on Convex Hull Trick!

Module Progress:

PrevNext