Nutella3001's blog

By Nutella3001, history, 3 years ago, translation, In English

Statement: We have an array A. Lets take every index i and find L[i] and R[i] — closest left and right index j such that A[j] >= A[i] respectively. Then I state that if for every i in 0..n-1 we sum min(i — L[i], R[i] — i) it will be O(N log N). It`s useful if we fix A[i] as the maximum number of segment and if the length of segments is fixed, we can naively iterate over all such segments.

Proof: Lets look at what we actually do. We iterate over i and look at L[i] and R[i] and count the elements to the closest side. If i — L[i] < R[i] — i, lets add segments (i — 1, i), (i — 2, i), ... , (L[i] + 1, i). Else lets add segments (i, i + 1), (i, i + 2), ... (i, R[i] — 1). In all of these segments let the endpoint that is equal to i be the red color and to the other endpoint to be the black color. Obviously this sum we are trying to prove is the number of segments = number of black points. Lets for every i calculate the maximum number of times that it can be the black end of segment. Let index j be the corresponding red end of such segment. I will prove for j > i, because for j < i its symmetrical. Lets take maximum j > i such that j can be red end of this segment. Then A[j] > A[j — 1] and A[j] > A[j — 2] ... A[j] > A[i]. So now lets take second maximum j such than j can be red end of this segment. Lets call the maximum j j1, second maximum j2. Notice that j2 — i <= j1 — j2. Because otherwise we wouldn`t take j2 with i, consequently 2 * j2 <= j1 + i. Consequently the number of such j s is maximum log n.

Usage: The most beautiful usage of this I have recently seen in task https://codeforces.com/problemset/problem/1175/F. I was thinking about hashes, etc. , but there is a solution just fixing the maximum of permutation, let it be A[i], find L[i], R[i] and iterate all segments with length A[i] that include i, but neither L[i] nor R[i]. Notice that it`s even less that described above so we can explicitly get our candidates to be the permutations and their number is <= N log N.

You can also check this task https://codeforces.com/contest/1156/problem/E , the same idea is used there in analysis.

Full text and comments »

  • Vote: I like it
  • +114
  • Vote: I do not like it