Frequent values#3838

Frequent values (Editorial)

The sequence is sorted in non-decreasing order, so equal elements stand next to each other and form blocks. The number of occurrences of a value on the segment [l; r] equals the length of the intersection of its block with this segment.

Array . Let \mathit{cnt}_i be the index of the element a_i inside its block, that is, the number of elements equal to a_i from the beginning of the block up to position inclusive:

For example, for a = (3, 3, 5, 9, 9, 9, 9, 10, 10) we get \mathit{cnt} = (1, 2, 1, 1, 2, 3, 4, 1, 2). Inside a block, the values of are successively 1, 2, 3, \ldots, so the largest of them is at the last element of the block and equals the length of the block:

Let us build a segment tree on the array that computes the maximum on a segment.

Answering a query. Consider the query [l; r]. If a_l = a_r, then all elements of the segment are equal, and the answer is r - l + 1.

Otherwise, the segment intersects at least two blocks. Let be the last position of the block containing a_l. The segment [l; r] is split into two parts:

Thus, the answer to the query is

\max\bigl(\mathit{LeftEnd} - l + 1, \max(\mathit{cnt}_{\mathit{LeftEnd}+1}, \ldots, \mathit{cnt}_r)\bigr)

The values of cannot be used for the first block: it may start to the left of position , and then includes elements that do not belong to the segment. In the figure \mathit{cnt}_3 = 3, although the value occurs only twice on the segment .

Binary search. The position precedes the first element of the segment that is greater than a_l, and it is found by binary search (the function upper_bound). The right boundary of the last block is not needed, so a single binary search is enough.

Solution without binary search. The position can be computed in advance. Let \mathit{last}_i be the last position of the block containing position . Scanning the positions from right to left, we get \mathit{last}_n = n, and for i < n we have \mathit{last}_i = \mathit{last}_{i+1} if a_i = a_{i+1}, and \mathit{last}_i = i otherwise. Then \mathit{LeftEnd} = \mathit{last}_l, and the condition a_l = a_r is equivalent to the inequality \mathit{last}_l \ge r.

Complexity. The arrays , and the segment tree are built in . A query consists of a binary search (or an access to the array ) and a maximum query to the segment tree, so it takes O(\log n). The total complexity of a test is O(n + q \log n).

Example

Let us consider the example. The array and the array built from it are as follows:

1

2

3

4

5

6

7

8

9

10

\boldsymbol{a_i}

1

1

1

1

3

10

10

10

\boldsymbol{\mathit{cnt}_i}

1

2

1

2

3

4

1

1

2

3

The array consists of four blocks: , (1, 1, 1, 1), and (10, 10, 10).

Query . Since a_2 = -1 \ne a_3 = 1, we find \mathit{LeftEnd} = 2. The first part contains one occurrence, and the maximum of on the segment is . The answer is \max(1, 1) = 1.

Query . We find \mathit{LeftEnd} = 2. The first part contains occurrences, and the maximum of on the segment is \max(1, 2, 3, 4, 1, 1, 2, 3) = 4. The answer is \max(2, 4) = 4: the value occurs times.

Query . We find \mathit{LeftEnd} = 6:

The first part contains occurrences of the value , and the maximum of on the segment is . The answer is \max(2, 3) = 3. Note that \mathit{cnt}_5 = 3 and \mathit{cnt}_6 = 4: these values include the elements a_3 and a_4, which lie outside the segment. If we computed the maximum of on the whole segment , we would get the wrong answer .

Algorithm Implementation

The input sequence is stored in the array , and the indices of the elements inside their blocks in the array . Elements are numbered from . The segment tree for the maximum is stored in the array of length 4 \cdot \mathit{MAX}.

int a[MAX], cnt[MAX];
int SegTree[4 * MAX];

The function BuildTree builds a segment tree for the maximum on the array . Vertex corresponds to the segment [\mathit{lpos}; \mathit{rpos}].

void BuildTree(int v, int lpos, int rpos)
{
  if (lpos == rpos)
  {
    SegTree[v] = cnt[lpos];
    return;
  }

  int mid = (lpos + rpos) / 2;
  BuildTree(2 * v, lpos, mid);
  BuildTree(2 * v + 1, mid + 1, rpos);
  SegTree[v] = max(SegTree[2 * v], SegTree[2 * v + 1]);
}

The function GetMax returns the maximum of the elements of the array on the segment [\mathit{left}; \mathit{right}]. For an empty segment it returns — the neutral element, since all values of are positive.

// Maximum on the segment [left; right],
// vertex v corresponds to [lpos; rpos]
int GetMax(int v, int lpos, int rpos, int left, int right)
{
  if (left > right) return 0;
  if ((lpos == left) && (rpos == right)) return SegTree[v];

  int mid = (lpos + rpos) / 2;
  return max(GetMax(2 * v, lpos, mid, left, min(mid, right)),
         GetMax(2 * v + 1, mid + 1, rpos, max(left, mid + 1), right));
}

The main part of the program. Process the tests while n \ne 0. Read the number of queries and the sequence .

while (scanf("%d", &n) == 1 && n)
{
  scanf("%d", &q);
  for (i = 1; i <= n; i++)
    scanf("%d", &a[i]);

Compute the array . If an element equals the previous one, its index in the block is one greater; otherwise, a new block starts with it, and its index is . The condition i > 1 is checked first, so we never go beyond the array.

  // cnt[i] – index of a[i] inside its block of equal elements
  for (i = 1; i <= n; i++)
    cnt[i] = (i > 1 && a[i] == a[i - 1]) ? cnt[i - 1] + 1 : 1;

Build the segment tree on the array .

  BuildTree(1, 1, n);

Process the queries one by one. If a_l = a_r, then the segment lies inside one block, and the answer is r - l + 1.

  while (q--)
  {
    scanf("%d %d", &l, &r);
    if (a[l] == a[r])      // the segment lies inside one block
      res = r - l + 1;

Otherwise, find by binary search. The function upper_bound returns a pointer to the first element of the segment [l; r] that is greater than a_l; the previous position is . The answer is the larger of two values: the number of occurrences of a_l in the first block and the maximum of on the segment [\mathit{LeftEnd} + 1; r].

    else
    {
      // LeftEnd – end of the first block, segment [l; LeftEnd]
      int LeftEnd = (int)(upper_bound(a + l, a + r + 1, a[l]) - a) -1;

      // the first block and the other blocks starting inside the segment
      res = max(LeftEnd - l + 1, GetMax(1, 1, n, LeftEnd + 1, r));
    }

Print the answer to the query.

    printf("%d\n", res);
  }
}

Algorithm Implementation — without Binary Search

Instead of binary search, let us compute in advance for each position the value — the last position of the block containing position .

The input sequence is stored in the array , the indices of the elements inside their blocks in the array , and the ends of the blocks in the array . Elements are numbered from . The segment tree for the maximum is stored in the array of length 4 \cdot \mathit{MAX}.

#define MAX 100010
int a[MAX], last[MAX], cnt[MAX];
int SegTree[4 * MAX];

The function BuildTree builds a segment tree for the maximum on the array . Vertex corresponds to the segment [\mathit{lpos}; \mathit{rpos}].

// Build a segment tree for the maximum on the array cnt
void BuildTree(int v, int lpos, int rpos)
{
  if (lpos == rpos)
  {
    SegTree[v] = cnt[lpos];
    return;
  }

  int mid = (lpos + rpos) / 2;
  BuildTree(2 * v, lpos, mid);
  BuildTree(2 * v + 1, mid + 1, rpos);
  SegTree[v] = max(SegTree[2 * v], SegTree[2 * v + 1]);
}

The function GetMax returns the maximum of the elements of the array on the segment [\mathit{left}; \mathit{right}]. For an empty segment it returns — the neutral element, since all values of are positive.

// Maximum on the segment [left; right],
// vertex v corresponds to [lpos; rpos]
int GetMax(int v, int lpos, int rpos, int left, int right)
{
  if (left > right) return 0;
  if ((lpos == left) && (rpos == right)) return SegTree[v];

  int mid = (lpos + rpos) / 2;
  return max(GetMax(2 * v, lpos, mid, left, min(mid, right)),
         GetMax(2 * v + 1, mid + 1, rpos, max(left, mid + 1), right));
}

The main part of the program. Process the tests while n \ne 0. Read the number of queries and the sequence .

while (scanf("%d", &n) == 1 && n)
{
  scanf("%d", &q);
  for (i = 1; i <= n; i++)
    scanf("%d", &a[i]);

Compute the array . If an element equals the previous one, its index in the block is one greater; otherwise, a new block starts with it, and its index is . The condition i > 1 is checked first, so we never go beyond the array.

  // cnt[i] – index of a[i] inside its block of equal elements
  for (i = 1; i <= n; i++)
    cnt[i] = (i > 1 && a[i] == a[i - 1]) ? cnt[i - 1] + 1 : 1;

Compute the ends of the blocks by scanning the positions from right to left. If a[i] = a[i + 1], then position belongs to the same block as position i + 1, and \mathit{last}[i] = \mathit{last}[i + 1]. Otherwise, the block ends at position . The condition i < n is checked first, so we never go beyond the array.

  // last[i] – end of the block containing position i
  for (i = n; i >= 1; i--)
    last[i] = (i < n && a[i] == a[i + 1]) ? last[i + 1] : i;

Build the segment tree on the array .

  BuildTree(1, 1, n);

Process the queries one by one. If the block containing position ends no earlier than position (\mathit{last}[l] \ge r), then the whole segment lies inside one block, and the answer is r - l + 1.

  while (q--)
  {
    scanf("%d %d", &l, &r);
    if (last[l] >= r)      // the segment lies inside one block
      res = r - l + 1;

Otherwise, the first block ends at position , and the value a_l occurs on the segment \mathit{last}[l] - l + 1 times. The other blocks occupy the segment [\mathit{last}[l] + 1; r], and the largest number of occurrences among them is returned by the function GetMax.

    else
      res = max(last[l] - l + 1, GetMax(1, 1, n, last[l] + 1, r));

Print the answer to the query. A query takes O(\log n) — the time of one query to the segment tree.

    printf("%d\n", res);
  }
}

Algorithm Implementation — RMQ

Since 2^{16} \le 10^5 < 2^{17}, the exponent in the sparse table does not exceed , and \mathit{LOGMAX} = 17 is enough for the second dimension.

#define MAX 100010
#define LOGMAX 17

The input sequence is stored in the array , and elements are numbered from . The value is the index of the element inside its block of equal elements. The array contains the values \mathit{lg2}[\mathit{len}] = \lfloor \log_2 \mathit{len} \rfloor, and is the sparse table.

int a[MAX], b[MAX], lg2[MAX];
int mas[MAX][LOGMAX];

The function Build_RMQ_Array builds the sparse table on the array : \mathit{mas}[i][j] is the maximum of the elements of on the segment [i; i + 2^j - 1]. The table stores the maximum values themselves rather than their indices: the position of the maximum is not needed in this problem.

void Build_RMQ_Array(void)
{
  for (int i = 1; i <= n; i++) mas[i][0] = b[i];
  for (int j = 1; 1 << j <= n; j++)
    for (int i = 1; i + (1 << j) - 1 <= n; i++)
      mas[i][j] = max(mas[i][j - 1], mas[i + (1 << (j - 1))][j - 1]);
}

The function RMQ returns the maximum of the elements b_i, \ldots, b_j in . The exponent k = \lfloor \log_2 (j - i + 1) \rfloor is taken from the array , and the segment is covered by two segments of length 2^k.

int RMQ(int i, int j)
{
  int k = lg2[j - i + 1];
  return max(mas[i][k], mas[j - (1 << k) + 1][k]);
}

The main part of the program. Fill the array once for all lengths up to . It does not depend on the input data and is used in all tests.

// lg2[len] = [log2(len)]
for (i = 2; i < MAX; i++) lg2[i] = lg2[i / 2] + 1;

Process the tests while n \ne 0. Read the number of queries .

while (scanf("%d", &n) == 1 && n)
{
  scanf("%d", &q);

Read the sequence and simultaneously build the array . The first element starts a block, so b[1] = 1. If an element equals the previous one, its index in the block is one greater than the index of the previous element; otherwise, a new block starts with it, and b[i] = 1.

  // b[i] – index of a[i] inside its block of equal elements
  scanf("%d", &a[1]); b[1] = 1;
  for (i = 2; i <= n; i++)
  {
    scanf("%d", &a[i]);
    b[i] = (a[i] == a[i - 1]) ? b[i - 1] + 1 : 1;
  }

Build the sparse table on the array in O(n \log n).

  Build_RMQ_Array();

Process the queries one by one. If a_{\mathit{Left}} = a_{\mathit{Right}}, then all elements of the segment are equal, and the answer is \mathit{Right} - \mathit{Left} + 1.

  while (q--)
  {
    scanf("%d %d", &Left, &Right);
    if (a[Left] == a[Right])     // the segment lies inside one block
      res = Right - Left + 1;

Otherwise, find by binary search — the last position of the block containing a_{\mathit{Left}}. The function upper_bound returns a pointer to the first element of the segment [\mathit{Left}; \mathit{Right}] that is greater than a_{\mathit{Left}}. Such an element exists, since a_{\mathit{Right}} > a_{\mathit{Left}}, and the previous position is .

The value a_{\mathit{Left}} occurs on the segment \mathit{LeftEnd} - \mathit{Left} + 1 times. All other blocks start inside the segment, so the values of on [\mathit{LeftEnd} + 1; \mathit{Right}] are counted from the beginning of these blocks and equal the numbers of occurrences inside the segment. The largest of them is returned by RMQ. The answer is the larger of the two values.

    else
    {
      // LeftEnd – end of the first block, segment [Left; LeftEnd]
      int LeftEnd =
         (int)(upper_bound(a + Left, a + Right + 1, a[Left]) - a) - 1;
      res = max(LeftEnd - Left + 1, RMQ(LeftEnd + 1, Right));
    }

Print the answer to the query. A query takes O(\log n) — the time of the binary search; the maximum query takes .

    printf("%d\n", res);
  }
}