视频加载失败

Fundamental Principles of Constant-Factor Optimization in OI

3798 字
19 分钟
Fundamental Principles of Constant-Factor Optimization in OI
Fundamental Principles of Constant-Factor Optimization in OI

Introduction#

We already understand the basic idea of time complexity: it describes an algorithm’s running time quantitatively as a function of the length of its input string (usually ). We also know that time complexity is normally written with big-O notation , with constant factors and lower-order terms omitted. Most of the time, this notation does its job—it tells us whether an algorithm is efficient or inefficient, how efficient or inefficient it is, and whether a given input can produce a result within the time limit (usually one second). But that is only most of the time.

Sometimes, however, you will find that you used the correct algorithm on a problem. You analyze the time complexity, find that it is such and such, and conclude that for the given range of it should just barely pass. So why does the judge still report that your code timed out? You look at someone else’s solution, and it is exactly the same as yours (both in algorithm and in data maintenance)—it may even contain a lot of puzzling, seemingly useless logic. Why does theirs pass?

The answer is hidden in the very notation we trust so much: the “constant factor” that has been deliberately left out.

Consider the segment tree and the Fenwick tree, both with query complexity. The latter takes only about as long as the former. This shows how large a gap constant factors can create.

Neutralizing these negative effects is simple: use constant-factor optimization techniques. Some OIers have given this a short, cute nickname—“ka chang” (literally “squeezing the constant”).

The purpose of this article is to share commonly used constant-factor optimization strategies and, as far as possible, to explain from a low-level perspective why they can achieve optimizations on the order of a hundred milliseconds.

I/O Streams#

I/O streams, short for input/output streams, are the most commonly used tools in competitive programming. In C, the usual ones are scanf, printf, puts, getchar, and so on. In C++, besides those, cin, cout, and cerr are also common.

If you are a devoted C++ user who wants to stay faithful to C++ style and use C++ functions and I/O, this part is for you.

Optimizing cin and cout#

C++‘s I/O streams are cin and cout, implemented on top of the iostream library; C’s printf and scanf are based on the stdio library. Their underlying implementations differ, but to support both—that is, to allow the two styles of I/O to be mixed in the same source file—C++ deliberately synchronizes the two libraries and uses the stdio I/O buffers. Although this provides interoperability, it adds overhead. For problems with input on the order of , performance drops substantially.

We therefore call sync_with_stdio() from the ios namespace and pass false to unsynchronize them, improving performance. The price is that you cannot mix the two styles of I/O statements in one program.

tie() binds cin and cout, which means that when cout is flushed, cin waits, ensuring output has completed before input proceeds. In other words, cin waits for cout to finish writing before it reads new data.

Passing nullptr binds them to a null pointer, which unties them. The two no longer have to wait for each other during I/O (they can proceed concurrently), improving I/O efficiency.

The core code for this optimization is:

ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);

Optimizing Newline Output#

This is another trick that pure C++ users should know.

If you need to output a newline, you may use endl. That is not wrong, of course, but compared with writing the newline escape character \n directly, it is definitely inefficient. Here is why.

C++‘s ostream library implements endl like this:

template<typename _CharT, typename _Traits>
inline basic_ostream<_CharT, _Traits>&
endl(basic_ostream<_CharT, _Traits>& __os)
{ return flush(__os.put(__os.widen('\n'))); }

It appends a wide-character '\n' to the output stream and then calls flush to flush the buffer. The widen function that produces the wide character has to consult the current machine’s locale to decide how to convert it. Its intent is good—it lets programs handle multilingual I/O more robustly—but in competitive programming it becomes dead weight that slows the program down.

In summary, when your code needs to output many lines, prefer \n over endl, or use the macro #define endl '\n'.

Seeing the Difference in Practice

Luogu’s sparse table template problem has a very large volume of I/O. You can compare performance before and after the optimization.

Arithmetic#

Bitwise Replacements#

You may have heard the trick that “bitwise operations reduce running time.” There is some truth to it.

Bitwise operations fit naturally with the underlying hardware: they act directly on binary digits, and modern CPUs usually have dedicated hardware support for them, with very short instruction latency. Multiplier and divider circuits use more complex strategies for multiplication and division and take longer; if they are used frequently, the performance difference becomes significant.

So if you want a multiplication or division (especially division) to keep only the integer part, as in the binary-search line int m = (l + r) / 2;, you can replace it with the corresponding bitwise operation—in this case, int m = (l + r) >> 1;.

Here are several common examples:

  1. Checking parity: x & 1. If the result is true, the number is odd; if false, it is even.
  2. Absolute value (for int): (x ^ (x >> 31)) - (x >> 31). It is not hard to see that for the result is . For , it first flips all bits and then subtracts (because the sign bit is the 32nd bit and is for negative numbers), which is equivalent to flipping all bits and adding one—that is, negating the number. Of course, you need to adjust this for different data types; for long long, use (x ^ (x >> 63)) - (x >> 63).
  3. Modulo : x & ((1 << n) - 1). This one is less widely known. Let with ; then . From the perspective of binary digits, if any bit at position or above in the binary representation of is , the value contributed by those bits is a multiple of , since each left shift multiplies the number by . The lower bits form the remainder , so we only need to extract them by ANDing with an -bit number consisting entirely of ones ().
  4. Binary search: int mid = (l + r) >> 1. Although compilers often turn some multiplications and divisions into bitwise operations, they will not do so here when l and r are both int. The reason is that the compiler cannot guarantee the sum is non-negative, and right-shifting a negative number is not equivalent to dividing it by . So when you can guarantee a non-negative result, you can manually replace division with a right shift.

Note that bitwise operators have different precedence from ordinary arithmetic operators. Use plenty of parentheses to make sure the expression matches your reasoning.

Modulo Optimization#

In a computer, modulo is based on division, so it also suffers from the poor performance of division. Here are several ways to optimize modulo operations.

Using Modulo Less Often#

For example, consider this line from matrix multiplication with modulo:

res.mat[i][j] += ((l.mat[i][k] % MOD) * (r.mat[k][j] % MOD)) % MOD

When implementing matrix multiplication modulo MOD, we can be sure that after each multiplication, every matrix element lies in . Therefore the modulo operations inside the two inner parentheses are unnecessary; change it to:

res.mat[i][j] += l.mat[i][k] * r.mat[k][j] % MOD

and that is enough.

A True Story

I once used the version with more modulo operations on a problem and got TLE. After optimizing it to the latter version, it passed comfortably. Clearly modulo operations have a significant impact on performance.

Replacing Modulo with Subtraction#

I am sure everyone can write the corresponding code from the heading alone, so I will not include it. Its effect is mediocre, however, and negative numbers require special handling. Rather than spending a lot of effort writing a loop, you are better off just using %.

Barrett Modular Multiplication#

This algorithm was proposed by in 1986 to address the poor performance of cryptographic algorithms that perform many modular reductions.

In his paper Implementing Fast Modular Reduction via Precomputed Multiplication, Barrett described the implementation in detail. Compared with ordinary modular arithmetic, the core of his method is to eliminate division, which is extremely slow.

Returning to the essence of modulo: computing means finding in the equation (, ). The method we use when computing modulo by hand can be written as:

Computing the reciprocal of involves division, which we want to replace. Consider the following approximation:

Then , and we usually take . In the earlier modulo expression, ; substituting this back gives the result.

However, no matter how we choose , there will always be error: the approximation sign remains an approximation and can never become a true equality in the mathematical sense. But remember that computer modulo operates on integers—a discrete domain—so in practice it is sometimes possible for the approximation to become exact.

Consider an error and . Then the approximation satisfies . To minimize the difference between the approximation and the true value, it is enough to choose as large as possible.

Returning to the original expression, the remainder obtained by Barrett modular multiplication is , and it satisfies the following relation with the true result :

Thus only one conditional correction is needed: if , set . The key code is:

int mod(int x, int p) {
int t = ((long long) x * p) >> 31;
x = x - (long long) t * p;
return x >= p ? x - p : x;
}

Choosing Data Types#

In C++, arithmetic on long long is slower than on int. So, as long as the data range permits, use int instead of unnecessary long long. If a multiplication may exceed the range of a normal integer, cast to long long for the intermediate step and then cast back to int.

Control Flow and Loops#

Choosing Between if and switch#

When there are many branches and the case values are dense, switch executes faster than if.

For dense cases, the compiler records each case using a method similar to radix sort, giving complexity; for sparse cases, it uses binary search, giving complexity.

The more branches there are, the greater the advantage of switch. In fact, compilers optimize dense multi-branch if chains into switch.

Loop Unrolling#

At the assembly level, each loop iteration goes through the following sequence:

.L3:
add rdx, [rax] ; loop body computation
add rax, 8 ; advance pointer
cmp rax, rcx ; compare with bound
jne .L3 ; conditional jump

But if we unroll it four times, it becomes:

.L3:
add rdx, [rax]
add rdx, [rax+8]
add rdx, [rax+16]
add rdx, [rax+24]
add rax, 32 ; advance pointer by 32 at once
cmp rax, rcx ; one comparison
jne .L3 ; one jump

Clearly, the second version increases the proportion of instructions doing actual computation and dilutes the cost of loop control. This is what it means to spend effort where it really pays off.

In addition, modern CPUs are superscalar: they can issue multiple independent instructions per clock cycle, provided those instructions do not depend on one another—in other words, they can sometimes be computed in parallel.

In the second assembly version, the four add instructions are mutually independent and can run at the same time. Four units of work in the time of one—that is where the time is saved. Of course, more unrolling is not always better. On one hand, it hurts readability and makes debugging harder; on the other, more live variables can cause register spills, producing a negative optimization. Unrolling times is generally recommended.

Loop unrolling helps most when the loop runs many times and the body is simple.

A classic example is multiplying two matrices: no loop is needed—four multiply-add computations suffice.

CPU Warm-Up#

A few classmates in the computer lab and I especially like to insert an empty loop of iterations into our simulated annealing code, and sometimes it really does speed things up.

If you are worried that the loop itself will slow execution, rest assured: in microcontroller design, the following delay function is commonly used:

void DelayNS(int ns) {
for (int i = 0; i < ns; i++) {
for (int j = 1; j <= 50000; j++);
}
}

In other words, every empty iterations corresponds to one nanosecond. A loop on the order of iterations has a negligible effect on the code’s execution efficiency.

The reason this code improves performance lies in the online judge itself.

An OJ allocates judging resources on its servers. To save power, modern CPUs run at lower frequencies and voltages when idle or lightly loaded. When a computational load appears, the frequency does not rise immediately; there is a gradual ramp-up process.

This warm-up code does exactly what its name suggests: the load it generates prompts the CPU’s frequency governor to raise the clock. By the time the loop ends and the main code runs, the CPU frequency has already increased, so the main block naturally executes faster.

Tested in Practice

Some benchmarking procedures deliberately include such empty loops to keep the CPU at its maximum frequency and reduce measurement error. Glibc’s benchmark code has included warm-up code like this.

Keywords#

Symbolic, Compile-Time, and Read-Only Constants#

Compare the following three definitions:

#define N 100010
const int N = 100010;
constexpr int N = 100010; // C++11 and later

They are, respectively, a symbolic constant, a read-only constant, and a compile-time constant. Before C++11, the const keyword carried both meanings—“read-only (unchangeable)” and “constant.” Starting with that standard, the constant-expression keyword constexpr was introduced to take over the “constant” role.

In terms of efficiency: symbolic constant = compile-time constant > read-only constant = variable.

We are familiar with how macros work: textual substitution at compile time.

#define N 100010
int a[N];

After compilation, this code is equivalent to:

int a[100010];

Compile-time constants work similarly and therefore achieve efficiency close to symbolic constants. A read-only constant, by contrast, behaves like an ordinary variable: its value must be loaded from memory by address. It merely has the extra property of being unchangeable.

After assembly, compile-time constants appear as immediate operands, whereas ordinary constants may still be loaded with a normal memory read. This is where the efficiency difference comes from.

So if your judge uses C++11 or later, define constants with constexpr rather than const.

Misconceptions About inline and register#

These optimizations appear frequently in OIers’ code.

Inlining uses the inline keyword. When you inline a function, the compiler replaces the call with the function body, for example:

inline int max(int a, int b) {
return a > b ? a : b;
}
int main() {
int a = 100, b = 90;
// In the source:
int c = max(a, b);
// After inlining:
int c = a > b ? a : b;
return 0;
}

Why does inlining sometimes improve performance? First, at the assembly level, a function call has the following fixed costs:

call func ; push return address, jump
; inside func:
push rbp ; set up stack frame
mov rbp, rsp
sub rsp, N ; allocate stack space for locals
... ; function body
mov rsp, rbp ; destroy stack frame
pop rbp
ret ; pop return address, jump back

When a small function such as max above is inlined, the corresponding stack-frame setup and space allocation no longer happen. In other words, when the fixed cost of calling a function exceeds the cost of the computation itself, it is better to perform only the computation without the call—which is exactly what inlining does.

Second, after inlining, two previously separate pieces of code merge into one context. This lets the compiler optimize based on context and eliminate cold code, yielding a small improvement.

Register variables, as the name suggests, are variables stored in registers. Registers are a high-speed storage area inside the CPU, so it is natural to think that marking a variable as a register variable speeds up access and thus improves efficiency. Today, this idea is simply wrong.

On modern x86-64 processors there are only 16 general-purpose registers. Declaring too many register variables consumes these precious resources, so variables that really would benefit from being in registers cannot be placed there, causing a negative optimization. Second, when compiling, the compiler runs a series of analyses over each variable’s lifetime and intelligently decides which variables are best placed in registers. In other words, even if you do not write the register keyword, the compiler will add it where it helps most.

In C++11, register was marked deprecated; in C++17, it was removed and survives only as a reserved word with no effect.

Library Functions#

Sorting Algorithms#

Every OIer knows that C++ has a sorting function called sort, which sorts data conveniently and efficiently. Its performance also seems much better than hand-written sorting algorithms (quicksort, merge sort, etc.).

Before explaining why it is so fast, let me ask: do you know which sorting algorithm sort uses underneath?

Some will say quicksort, because it is . That answer is only half right.

Under the hood, sort implements Introsort, a hybrid of three sorting algorithms.

Normally, it uses quicksort as the main algorithm for the sequence. But although quicksort has excellent average complexity, it degrades to on nearly sorted sequences or when pivots are chosen poorly—an unacceptable side effect.

So sort includes a stop-loss mechanism: when the recursion depth exceeds , it immediately switches to heapsort, pulling the worst-case complexity back to and providing a fallback that hand-written quicksort lacks.

There is another optimization for small ranges. When the range to sort is shorter than a threshold (which varies by compiler), it does not recurse further and instead uses insertion sort. Many people may wonder why an algorithm with average complexity is inserted into one whose overall complexity is near . In fact, continuing to recurse has the same drawback as not inlining a small function: the call overhead exceeds the cost of the computation. Moreover, near the end of sorting, the array is nearly sorted, making it easier for insertion sort to reach its best case. Also, is very small, so quadratic and linear complexity are not far apart, which is acceptable.

Overall, Introsort is: quicksort for large partitions, insertion sort for small ones, and heapsort as a fallback. Working together, the three make it faster than an ordinary hand-written sort.

The pivot-selection strategy in sort’s quicksort is also clever: it uses median-of-three, greatly reducing the chance of choosing a bad pivot.

STL#

bitset#

I believe every OIer, when first using bitset, is amazed by its wonderful complexity . After all, a boolean array or a vector<bool> can only achieve . How does bitset do better?

In a boolean array, each element occupies one byte (8 bits) to store a single 0/1 value—clearly a waste. bitset, as its name suggests, uses one bit to store each 0/1 value. That is an eightfold compression, which lets more data move in and out of cache (improving the cache hit rate) and improves efficiency. bitset is implemented roughly as several 64-bit integers concatenated into a contiguous array.

Another performance gain comes from its operations. To perform bitwise operations on a boolean array, we must iterate over it—at the assembly level, thousands of memory loads, reads, and arithmetic instructions. The “concatenated integers” design of bitset lets it operate on each block separately, so the number of operations equals the number of blocks rather than the total number of bits, greatly reducing the work.

When we define a bitset, bitset<N> uses a compile-time constant. This means the compiler knows its size and memory layout completely, opening the door to optimization. In fact, with -O2, bitset performs significantly better than vector<bool>.

map and unordered_map#

Arrays and Memory#

Rolling Arrays#

This optimization is mostly used in DP and is a space optimization technique. When the core DP transition depends on only a few recent states, there is no need to declare an array of length ; reusing a small array is enough.

Take the 0/1 knapsack template as an example. Considering the first items with maximum capacity , the transition is dp[i][j] = max(dp[i-1][j], dp[i-1][j-w[i]] + v[i]). The current state depends only on the previous state, so the first dimension can be rolled.

The first dimension depends only on state , so its size can be compressed to : one element stores the previous state, the other stores the current state, alternating. Rolling once gives:

int dp[2][M];
for (int i = 1; i <= n; i++) {
int cur = i & 1, prev = (i - 1) & 1;
for (int j = 0; j <= m; j++) {
dp[cur][j] = dp[prev][j];
if (j >= w[i])
dp[cur][j] = max(dp[cur][j], dp[prev][j - w[i]] + v[i]);
}
}

In fact, we can eliminate the first dimension entirely. The extreme rolled version is actually closer to how people write it during contests:

int dp[M] = {0};
for (int i = 1; i <= n; i++)
for (int j = m; j >= w[i]; j--) // Note the descending loop here
dp[j] = max(dp[j], dp[j - w[i]] + v[i]);

After rolling away one dimension, the inner loop changes from ascending to descending. Why descending? Because it guarantees that dp[j - w[i]] has not yet been updated in this round (with fixed), which naturally matches the 0/1 knapsack property that each item is chosen at most once. For the unbounded knapsack problem, where each item may be chosen arbitrarily many times, the loop over must be ascending.

Thus, after compressing dimensions with a rolling array, pay close attention to the update order between states and choose the loop direction appropriately.

This technique is more of an algorithmic optimization than a constant-factor optimization of a fixed algorithm, but I include it here for reference.

Memory Contiguity and Strided Access#

Note

This section was inspired by a reply from GGapa to my Luogu blog post Re: The Road to Constant-Factor Optimization from Scratch several years ago.

We notice that accessing two nearby elements of an array takes less time than accessing two distant ones. This is very intuitive: when the indices are far apart, the CPU has to move from one to the other step by step, which is naturally slower.

But the memory we mainly use is RAM—random-access memory. In theory, random access means reading any two pieces of data should take roughly the same time. The catch is the cache.

When we read an element of an array, the memory system pulls several adjacent elements into the cache. Accessing data in the cache (adjacent data) is faster; otherwise, it must be fetched from RAM, which is slower.

Modern CPUs may also predict your access pattern. When your indices follow an obvious pattern (a fixed stride), the CPU automatically brings data likely to be accessed next into the cache, speeding up access.

See my discussion post for the performance difference caused by memory contiguity. Please ignore the parts claiming that “CPU warm-up is just judge fluctuation.”

References#

  1. Zhihu @wYYSZL, A Brief Discussion of Constant-Factor Optimization Techniques in OI (Basically Complete)
  2. Luogu @JustPureH2O, Re: The Road to Constant-Factor Optimization from Scratch

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

Fundamental Principles of Constant-Factor Optimization in OI
https://justpureh2o.cn/articles/fundamental-principles-of-constant-factor-optimization-in-oi-en/
作者
JustPureH2O
发布于
2026-11-15
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
JustPureH2O
穷方圆平直之情,尽规矩准绳之用
公告
分类
标签
站点统计
文章
111
分类
19
标签
65
总字数
461,929
运行时长
0 天
最后活动
0 天前
站点信息
构建平台
Vercel
博客版本
Firefly vunknown
文章许可
CC BY-NC-SA 4.0
文章目录