#P15850. [NOISG 2026 Finals] Gemstones

[NOISG 2026 Finals] Gemstones

Problem Description

You are playing a puzzle game featuring nn gemstones in a row, numbered from 11 to nn from left to right. The ii-th gemstone has colour c[i]c[i].

At any point, you may select two adjacent gemstones of the same colour and delete them. Then, the gemstones on either side slide together to close the gap, possibly creating new adjacent pairs.

You will be given qq independent scenarios. In the jj-th scenario, you will only consider gemstones starting from gemstone l[j]l[j] and ending at gemstone r[j]r[j]. Assuming you perform an optimal sequence of deletions, what is the minimum number of gemstones that can be left behind?

Input Format

Your program must read from standard input.

The first line of input contains two space-separated integers nn and qq.

The second line of input contains nn space-separated integers c[1],c[2],,c[n]c[1], c[2], \ldots, c[n].

The next qq lines of input each contain two space-separated integers. The ii-th of these lines contains l[i]l[i] and r[i]r[i].

Output Format

Your program must print to standard output.

The output should contain qq lines. The ii-th of these lines should contain one integer, the answer to the ii-th scenario.

8 4
3 3 3 2 2 3 4 7
1 3
3 6
1 7
5 8
1
0
1
4
6 3
2 1 1 2 2 1
1 6
1 4
3 6
2
0
0

Hint

Sample Test Case 1 Explanation

The n=8n = 8 gemstones are shown in the diagram below.

:::align{center} :::

In the first scenario, only the first three gemstones should be considered. Deleting any two adjacent gemstones will leave exactly one behind, after which it is impossible to delete any more gemstones. Hence, the answer is 11.

In the second scenario, gemstones can be deleted in the following manner, leaving none behind:

:::align{center} :::

In the third scenario, gemstones can be deleted in the following manner, leaving one behind:

:::align{center} :::

In the fourth scenario, no gemstones can be deleted. Hence, the answer is 44.

Subtasks

For all test cases, the input will satisfy the following bounds:

  • 1n1061 \le n \le 10^6
  • 1q5000001 \le q \le 500\,000
  • 1c[i]1091 \le c[i] \le 10^9 for all 1in1 \le i \le n
  • 1l[j]r[j]n1 \le l[j] \le r[j] \le n for all 1jq1 \le j \le q

Your program will be tested on input instances that satisfy the following restrictions:

Subtask Score Additional Constraints
0 Sample test cases
1 2 c[1]=c[2]==c[n]c[1] = c[2] = \cdots = c[n]
2 5 Gemstones of the same colour form a contiguous subarray (If c[i]=c[j]c[i] = c[j] and i<ji < j, then c[i]=c[i+1]==c[j]c[i] = c[i+1] = \cdots = c[j])
3 9 n,q2000n, q \le 2000
4 l[j]=1l[j] = 1 for all 1jq1 \le j \le q
5 8 There are exactly two gemstones of each colour
6 16 c[i]2c[i] \le 2 for all 1in1 \le i \le n
7 18 n,q100000n, q \le 100\,000
8 15 n,q300000n, q \le 300\,000
9 23 No additional constraints