Official

C - First Come First Serve Editorial by endagorion


Let \(C_i = 0\) if customer \(i\) entered their name at time \(A_i\), and \(C_i = 1\) otherwise. Consider a resulting permutation \(P\), and suppose two different arrays \(C1\) and \(C2\) (as described above) result in \(P\). We argue that the array \(C\) defined by \(C_i = \min(C1_i, C2_i)\) also results in \(P\). Indeed, consider the first position \(i\) where \(C1\) and \(C2\) differ, say, \(C1_i = 0\) and \(C2_i = 1\). If we change \(C2_i\) to \(0\), the order will clearly not change, as there couldn’t be any entries between \(A_i\) and \(B_i\) (orthe permutations for \(C1\) and \(C2\) wouldn’t coincide). We can proceed in this way until both arrays are equal to \(C\).

It follows that for each permutation \(P\) there exists a unique array \(C\) such that no single element \(C_i\) can be changed from \(1\) to \(0\) while preserving the order. In other words, for each \(i\) such that \(C_i = 1\), there has to be at least one entry other than \(i\) between times \(A_i\) and \(B_i\). The number of arrays satisfying this condition is the answer.

One way to count such arrays is to use PIE. Suppose \(C_i = 1\), and the segment \([A_i, B_i]\) contains no other entries: in this case we say that there is a problem at \(i\). We PIE over sets of indices that simultaneously have problems.

Define \(L_i\) as the smallest \(j\) such that \(B_j > A_i\), and \(R_i\) as the largest \(j\) such that \(A_j < B_i\). If there is a problem at \(i\), then we must have \(C_{L_i} = \ldots = C_{i - 1} = 0\), \(C_i = \ldots = C_{R_i} = 1\). Note that for two indices \(i < j\), if \(R_i \geq L_j\), then there can’t be problems at \(i\) and \(j\) simultaneously. Thus, non-zero summands in PIE correspond to collections of disjoint segments \([L_i, R_i]\), with the weight of each collection being \(2^x (-1)^y\), where \(x\) is the number of indices uncovered by any segment, \(y\) is the number of segments. Computing the PIE sum is an easy \(O(N)\) DP.

posted:
last update: