Explain concept complexity-budget-estimation

This commit is contained in:
usaco site
2026-10-20 13:58:35 +00:00
parent a1a95c8963
commit 5772093741
3 changed files with 196 additions and 0 deletions
@@ -0,0 +1,164 @@
<!-- concept tags=complexity,constraints,time-limit,contest-strategy -->
# Estimating TLE from constraints (operations budget)
_Predict TLE before coding: plug the maximum input sizes into your algorithm's complexity and compare with a budget of about 10^8 simple C++ operations per second; checking takes O(1) time._
_Explained by claude-opus-5-5 on 20 October 2026._
## Intuition
**The problem.** You have an idea for a solution. You want to know *before* coding it whether it will run inside the time limit. Otherwise you get **TLE** (Time Limit Exceeded), meaning the judge killed your program because it was too slow.
**Why "just try it" is wrong.** The sample tests are tiny, so any algorithm passes them instantly. The judge's hidden tests use the *maximum* sizes from the statement. An $O(n^2)$ loop on $n = 10^3$ is instant. The same loop on $n = 2\cdot 10^5$ needs about $4 \cdot 10^{10}$ steps, which takes minutes.
**The idea that fixes it.** Treat time as a budget of operations. A modern judge runs compiled C++ at roughly $10^8$–$10^9$ simple operations per second. The low end is safe, and the high end is only reached by very tight loops. So:
$$\text{ops}(n_{\max}) \le 10^8 \times \text{TL in seconds} \quad\Rightarrow\quad \text{safe}$$
Plug the **largest** allowed input into your algorithm's complexity, ignoring constants, and compare the result with the budget.
This works in reverse too. Problem setters choose the constraints so that the intended complexity just fits. **So the constraints tell you which algorithm they want.** For example, $n \le 20$ suggests something over all subsets, and $n \le 5000$ suggests $O(n^2)$.
## How it works
### The procedure, every time
1. **Find the worst case** from the constraints: the largest $n$, $m$, $q$, values and number of tests. Note any guarantee such as "sum of $n$ over all tests $\le 2\cdot 10^5$".
2. **Write your algorithm's cost as a formula** in those quantities, for example $q \log^2 n$ or $n \cdot m$. Count the work of every loop and every data-structure call.
3. **Plug in the numbers and compare with the budget** $B = 10^8 \times \text{TL}$:
- $\le B$: **safe**. Write it without worrying.
- between $B$ and $10 B$: **risky**. It passes only with simple loops, contiguous arrays and few `%` or divisions. It fails with `map`, `set`, recursion or heavy objects.
- $> 10 B$: **TLE**. Find a better algorithm.
### The reverse table: from $n$ to the complexity they expect
This table is the same rule solved for $n$. It assumes 1 second.
| max $n$ | intended complexity | operations at max |
|---|---|---|
| $\le 10$–$11$ | $O(n!)$, $O(n \cdot n!)$ | $\approx 4\cdot 10^7$ |
| $\le 20$ | $O(2^n \cdot n)$ bitmask DP | $\approx 2\cdot 10^7$ |
| $\le 40$ | $O(2^{n/2})$ meet in the middle | $\approx 10^6$ per half |
| $\le 100$ | $O(n^4)$ | $10^8$ |
| $\le 500$ | $O(n^3)$ | $1.25\cdot 10^8$ |
| $\le 5000$ | $O(n^2)$ | $2.5\cdot 10^7$ |
| $\le 10^5$ | $O(n\sqrt n)$, $O(n \log^2 n)$ | $3\cdot 10^7$ |
| $\le 10^6$ | $O(n \log n)$ | $2\cdot 10^7$ |
| $\le 10^7$–$10^8$ | $O(n)$, often with a tiny constant | $10^7$–$10^8$ |
| $\le 10^{12}$ and up | $O(\sqrt n)$, $O(\log n)$, $O(1)$ | small |
Read it in both directions:
- "$n \le 5000$" almost shouts $O(n^2)$.
- "$n \le 20$" shouts subsets.
- "$n \le 10^{18}$" means you may not even loop to $n$.
### What counts as one "operation"
An operation is one cheap step: an addition, a comparison, an array read in cache.
- **Costly steps, each worth several operations:** `%` and `/` on `long long`, which are 20–40 cycles. Also cache misses from random memory access, and allocation inside loops.
- **Each call is $\log n$ operations with a big constant:** `set`, `map`, `priority_queue`, `lower_bound`.
- **Each call is $O(1)$ on average with a large constant:** `unordered_map`.
That is why the safe line is $10^8$, not the $10^9$ cycles a CPU actually runs.
### Measuring instead of guessing
If your estimate is in the risky zone, generate a maximum-size, worst-shaped test and time it. The `Timer` struct below does this. Leave yourself a 2× margin, because judges can be slower than your machine.
## Walkthrough
**Step 1.** **Read the constraints.** Suppose $n \le 2\cdot 10^5$, the time limit is 1 s, and there are up to $t = 10^4$ tests with $\sum n \le 2\cdot 10^5$.
The axis is logarithmic, so each tick is $100\times$ the previous one.
- The green dashed line is the safe budget, $10^8$.
- The red dashed line, $10^9$, is where even tight loops fail.
The blue bar is $n$ itself. Reading the input once is free.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 380"><text x="20" y="28" font-family="sans-serif" font-size="15" fill="currentColor">n = 2·10^5, TL = 1 s</text><line x1="440" y1="60" x2="440" y2="340" stroke="#22c55e" stroke-width="2" stroke-dasharray="5 4"/><line x1="480" y1="60" x2="480" y2="340" stroke="#ef4444" stroke-width="2" stroke-dasharray="5 4"/><text x="436" y="55" text-anchor="end" font-family="sans-serif" font-size="13" fill="currentColor">safe ≤1e8</text><text x="484" y="55" font-family="sans-serif" font-size="13" fill="currentColor">TLE ≥1e9</text><text x="110" y="97" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n</text><rect x="120" y="80" width="212" height="24" fill="#3b82f6"/><text x="338" y="97" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">2e5</text><line x1="120" y1="340" x2="600" y2="340" stroke="currentColor"/><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="120" y="360">1</text><text x="200" y="360">1e2</text><text x="280" y="360">1e4</text><text x="360" y="360">1e6</text><text x="440" y="360">1e8</text><text x="520" y="360">1e10</text><text x="600" y="360">1e12</text></g></svg>
```
**Step 2.** **Try the brute force, $O(n^2)$.** Plugging in $n = 2\cdot 10^5$ gives $n^2 = 4 \cdot 10^{10}$. That is $400\times$ the safe budget, which means minutes of running time. Reject it before writing a line.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 380"><text x="20" y="28" font-family="sans-serif" font-size="15" fill="currentColor">n = 2·10^5, TL = 1 s</text><line x1="440" y1="60" x2="440" y2="340" stroke="#22c55e" stroke-width="2" stroke-dasharray="5 4"/><line x1="480" y1="60" x2="480" y2="340" stroke="#ef4444" stroke-width="2" stroke-dasharray="5 4"/><text x="436" y="55" text-anchor="end" font-family="sans-serif" font-size="13" fill="currentColor">safe ≤1e8</text><text x="484" y="55" font-family="sans-serif" font-size="13" fill="currentColor">TLE ≥1e9</text><text x="110" y="97" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n</text><rect x="120" y="80" width="212" height="24" fill="#3b82f6"/><text x="338" y="97" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">2e5</text><text x="110" y="142" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n²</text><rect x="120" y="125" width="424" height="24" fill="#ef4444"/><text x="550" y="142" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">4e10</text><line x1="120" y1="340" x2="600" y2="340" stroke="currentColor"/><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="120" y="360">1</text><text x="200" y="360">1e2</text><text x="280" y="360">1e4</text><text x="360" y="360">1e6</text><text x="440" y="360">1e8</text><text x="520" y="360">1e10</text><text x="600" y="360">1e12</text></g></svg>
```
**Step 3.** **Try sorting plus binary search, $O(n \log n)$.** Since $\log_2(2\cdot 10^5) \approx 18$, the cost is about $3.6\cdot 10^6$ operations. That is far under the budget, so even `set` or `map` constants are fine. This is very likely the intended complexity for $n = 2\cdot 10^5$.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 380"><text x="20" y="28" font-family="sans-serif" font-size="15" fill="currentColor">n = 2·10^5, TL = 1 s</text><line x1="440" y1="60" x2="440" y2="340" stroke="#22c55e" stroke-width="2" stroke-dasharray="5 4"/><line x1="480" y1="60" x2="480" y2="340" stroke="#ef4444" stroke-width="2" stroke-dasharray="5 4"/><text x="436" y="55" text-anchor="end" font-family="sans-serif" font-size="13" fill="currentColor">safe ≤1e8</text><text x="484" y="55" font-family="sans-serif" font-size="13" fill="currentColor">TLE ≥1e9</text><text x="110" y="97" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n</text><rect x="120" y="80" width="212" height="24" fill="#3b82f6"/><text x="338" y="97" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">2e5</text><text x="110" y="142" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n²</text><rect x="120" y="125" width="424" height="24" fill="#ef4444"/><text x="550" y="142" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">4e10</text><text x="110" y="187" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n log n</text><rect x="120" y="170" width="262" height="24" fill="#22c55e"/><text x="388" y="187" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">3.6e6</text><line x1="120" y1="340" x2="600" y2="340" stroke="currentColor"/><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="120" y="360">1</text><text x="200" y="360">1e2</text><text x="280" y="360">1e4</text><text x="360" y="360">1e6</text><text x="440" y="360">1e8</text><text x="520" y="360">1e10</text><text x="600" y="360">1e12</text></g></svg>
```
**Step 4.** **Try sqrt decomposition, $O(n\sqrt n)$.** Since $\sqrt{2\cdot 10^5} \approx 447$, the cost is about $9\cdot 10^7$, right at the safe line. It passes with plain arrays and tight loops, but can fail with heavy constants. This is the **risky zone**: measure a max test with `Timer` before submitting.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 380"><text x="20" y="28" font-family="sans-serif" font-size="15" fill="currentColor">n = 2·10^5, TL = 1 s</text><line x1="440" y1="60" x2="440" y2="340" stroke="#22c55e" stroke-width="2" stroke-dasharray="5 4"/><line x1="480" y1="60" x2="480" y2="340" stroke="#ef4444" stroke-width="2" stroke-dasharray="5 4"/><text x="436" y="55" text-anchor="end" font-family="sans-serif" font-size="13" fill="currentColor">safe ≤1e8</text><text x="484" y="55" font-family="sans-serif" font-size="13" fill="currentColor">TLE ≥1e9</text><text x="110" y="97" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n</text><rect x="120" y="80" width="212" height="24" fill="#3b82f6"/><text x="338" y="97" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">2e5</text><text x="110" y="142" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n²</text><rect x="120" y="125" width="424" height="24" fill="#ef4444"/><text x="550" y="142" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">4e10</text><text x="110" y="187" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n log n</text><rect x="120" y="170" width="262" height="24" fill="#22c55e"/><text x="388" y="187" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">3.6e6</text><text x="110" y="232" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n√n</text><rect x="120" y="215" width="318" height="24" fill="#f59e0b"/><text x="492" y="232" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">9e7</text><line x1="120" y1="340" x2="600" y2="340" stroke="currentColor"/><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="120" y="360">1</text><text x="200" y="360">1e2</text><text x="280" y="360">1e4</text><text x="360" y="360">1e6</text><text x="440" y="360">1e8</text><text x="520" y="360">1e10</text><text x="600" y="360">1e12</text></g></svg>
```
**Step 5.** **The multi-test trap.** The $O(n \log n)$ solution is correct, but suppose it calls `memset(cnt, 0, sizeof cnt)` on a 200 000-element array in every test. That costs $t \cdot 2\cdot 10^5 = 2\cdot 10^9$, which is TLE even though $\sum n$ is small.
Always add up the cost of anything that does not scale with that test's own $n$. Here the fix is to clear only the first $n$ entries.
```svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 380"><text x="20" y="28" font-family="sans-serif" font-size="15" fill="currentColor">t = 1e4 tests, Σn = 2·10^5</text><line x1="440" y1="60" x2="440" y2="340" stroke="#22c55e" stroke-width="2" stroke-dasharray="5 4"/><line x1="480" y1="60" x2="480" y2="340" stroke="#ef4444" stroke-width="2" stroke-dasharray="5 4"/><text x="436" y="55" text-anchor="end" font-family="sans-serif" font-size="13" fill="currentColor">safe ≤1e8</text><text x="484" y="55" font-family="sans-serif" font-size="13" fill="currentColor">TLE ≥1e9</text><text x="110" y="97" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n</text><rect x="120" y="80" width="212" height="24" fill="#3b82f6"/><text x="338" y="97" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">2e5</text><text x="110" y="142" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n²</text><rect x="120" y="125" width="424" height="24" fill="#ef4444"/><text x="550" y="142" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">4e10</text><text x="110" y="187" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n log n</text><rect x="120" y="170" width="262" height="24" fill="#22c55e"/><text x="388" y="187" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">3.6e6</text><text x="110" y="232" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">n√n</text><rect x="120" y="215" width="318" height="24" fill="#f59e0b"/><text x="492" y="232" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">9e7</text><text x="110" y="277" text-anchor="end" font-family="ui-monospace, monospace" font-size="14" fill="currentColor">t·memset</text><rect x="120" y="260" width="372" height="24" fill="#ef4444"/><text x="498" y="277" font-family="ui-monospace, monospace" font-size="13" fill="currentColor">2e9</text><line x1="120" y1="340" x2="600" y2="340" stroke="currentColor"/><g font-family="ui-monospace, monospace" font-size="13" fill="currentColor" text-anchor="middle"><text x="120" y="360">1</text><text x="200" y="360">1e2</text><text x="280" y="360">1e4</text><text x="360" y="360">1e6</text><text x="440" y="360">1e8</text><text x="520" y="360">1e10</text><text x="600" y="360">1e12</text></g></svg>
```
## Using it
```cpp
TimeBudget tb(1.0); // 1 second time limit
double n = 2e5, q = 2e5;
int a = tb.verdict(n * q); // 2 -> O(n*q) = 4e10, TLE
int b = tb.verdict(TimeBudget::nLogN(n)); // 0 -> 3.5e6, safe
int c = tb.verdict(TimeBudget::nSqrtN(n)); // 0 -> 8.9e7, safe but tight
int d = tb.verdict(TimeBudget::subsets(20));// 0 -> 2e7, bitmask DP fine
Timer t;
// solve(maxTest); // run on a generated worst-case input
cerr << t.ms() << " ms\n";
// Heuristic search that stops safely before a 2 s limit:
// while (t.ms() < 1800) { improve(); }
```
## Complexity
Reading the constraints and doing the arithmetic costs $O(1)$. It is a few multiplications that save you from writing the wrong solution.
- **`verdict` and the cost models:** $O(1)$ time and $O(1)$ memory. Each one is a formula.
- **`Timer`:** $O(1)$ per call. `steady_clock` reads are cheap, but in a tight search loop check the clock every ~1000 iterations rather than on every iteration.
- **Memory has its own budget, so check it too.** One `int` is 4 bytes and one `long long` is 8 bytes. A 256 MB limit holds about $6 \cdot 10^7$ ints or $3 \cdot 10^7$ long longs. So a $5000 \times 5000$ `long long` DP (200 MB) fits only barely, and a $10^4 \times 10^4$ one does not fit at all.
## When to reach for it
**Always, before coding.** It takes ten seconds and is the most useful habit in contests. Use it especially when:
- You have a working brute force and wonder whether it is enough. Many easy problems have $n \le 2000$, where $O(n^2)$ is fine, so it often is.
- You are stuck. Look at the constraints and read the intended complexity off the table. Then ask which known technique has that complexity:
- $O(n \log n)$ suggests sorting, segment trees or binary search.
- $O(2^n)$ suggests subsets or bitmask DP.
- $O(n^3)$ suggests interval DP or Floyd–Warshall.
- Two ideas compete. Pick the simplest one that fits the budget, not the asymptotically best one.
**Close alternatives:**
- **Measuring** with `Timer` on a generated max test. Prefer it when the estimate is in the risky zone ($10^8$–$10^9$) or when constants are unclear, such as hashing, recursion or heavy STL.
- **Thinking about memory** in the same way. Use it when the arrays are 2D or the DP tables are large.
- **Interpreted languages** like Python are about 30–100× slower. Divide the budget accordingly, to roughly $10^6$–$10^7$ per second.
## Pitfalls
- **Multiple test cases.** If $t \le 10^4$ and each $n \le 2\cdot 10^5$, check whether the statement guarantees $\sum n \le 2\cdot 10^5$. Without that guarantee even $O(n)$ per test is $2\cdot 10^9$. With it, anything that depends only on $n$ is fine.
- **Hidden per-test costs.** Even when $\sum n$ is bounded, `memset`, `vector(MAXN)` or a sieve redone inside each test costs $t \cdot \text{MAXN}$. Clear only the first $n$ entries, or build shared tables once before reading the tests.
- **Forgetting a factor.** $q$ queries each doing an $O(\log n)$ `set` operation inside an $O(\log n)$ binary search costs $q \log^2 n$, not $q \log n$. Multiply every nested level, including the cost of the library calls.
- **Several variables.** With an $n \times m$ grid and $q$ queries, the cost may be $n m$ (fine at $10^3 \times 10^3$) or $q \cdot n m$ (TLE). Plug in the maximum of each variable simultaneously, unless the statement says something like $n \cdot m \le 10^6$.
- **Constraints on values, not sizes.** $a_i \le 10^9$ forbids a counting array of size $\max a$, even when $n$ is small. Use sorting, coordinate compression or hashing instead.
- **Big constants.** `map`, `set`, `unordered_map`, recursion, `long long %` and `endl` (it flushes) can make a 'safe' $5\cdot 10^7$ run in 2 s.
- **Slow I/O.** Reading $10^6$ numbers with plain `cin` is slow. Add `ios::sync_with_stdio(false); cin.tie(nullptr);` and print `'\n'` instead of `endl`.
- **Average versus worst case.** Hash tables, naive quicksort and pivot-based tricks can be hacked with adversarial tests. Estimate with the worst case unless the randomness is your own.
- **Integer overflow in the estimate itself.** `n*n` with `int n = 2e5` overflows. Compute estimates in `double` or `long long`.
## Variations
- **Different time limits:** scale the budget linearly. With a 3 s limit you get about $3 \cdot 10^8$. A 0.5 s limit halves it, which often signals "no $\log$ factor, or a very light one".
- **Amortized costs:** add up the total work over the whole run, not the worst single step. For example, a two-pointer loop is $O(n)$ in total even though one step can move far, and DSU is close to $O(1)$ per operation.
- **Bitset speedup:** a `bitset<N>` operation processes 64 bits per machine word. That turns $O(n^2)$ or $O(n^3)$ into the same cost divided by 64, which is how $n = 2000$ cubic or $n = 5\cdot 10^4$ quadratic solutions pass.
- **Offline or sqrt tricks:** when $O(n \log n)$ is hard to find and $n \le 10^5$, the table says $O(n \sqrt n) \approx 3 \cdot 10^7$ is allowed. That is the budget behind Mo's algorithm and sqrt decomposition.
- **Recursion depth:** depth $10^6$ in DFS can overflow the stack. This is a memory limit rather than a time limit, but it is estimated the same way. Switch to an iterative version when the depth can reach $n \approx 10^5$–$10^6$.
- **Time-guarded heuristics:** in optimization or interactive problems, use `Timer` to search until about 90% of the time limit and then print the best answer found so far.
@@ -0,0 +1 @@
I woud like to know the TLE of a problem given its input array size (or any other kind of input)
@@ -0,0 +1,31 @@
// concept: complexity-budget-estimation
// Rough operations budget for C++: <= 1e8 simple ops per second is safe,
// up to ~1e9/s only for very tight loops, beyond that expect TLE.
struct TimeBudget {
double seconds; // time limit of the problem
explicit TimeBudget(double s = 1.0) : seconds(s) {}
// 0 = safe, 1 = risky (needs small constant), 2 = TLE. O(1).
int verdict(double ops) const {
if (ops <= 1e8 * seconds) return 0;
if (ops <= 1e9 * seconds) return 1;
return 2;
}
// Cost models for common complexities; n is a size (count), not an index. O(1) each.
static double lg(double n) { return max(1.0, log2(n)); }
static double nLogN(double n) { return n * lg(n); }
static double nSqrtN(double n) { return n * sqrt(n); }
static double subsets(double n) { return pow(2.0, n) * n; } // 2^n * n bitmask DP
static double perms(int n) { double f = 1; for (int i = 2; i <= n; i++) f *= i; return f * n; } // n! * n
};
// Wall-clock timer: time a max-size test locally, or stop a search before the limit.
struct Timer {
chrono::steady_clock::time_point st = chrono::steady_clock::now();
// Milliseconds since construction or last reset(). O(1).
double ms() const {
return chrono::duration<double, milli>(chrono::steady_clock::now() - st).count();
}
void reset() { st = chrono::steady_clock::now(); }
};