You are on page 1of 3

Magic Cards

Time complexity: 1 second


Memory complexity: 256MB

Birzhan has N cards, numbered from 1 to N. Every card has each number from 1 to M written
on it. Some numbers exist on the front side of the card and some on the back side. No number
exists on both the sides of a card at the same time. These cards are placed on the table in a
row such that only one side is visible. Birzhan is allowed to flip them any number of times.

Now, Birzhan has to answer Q queries, each of them consisting of two integers l and r. We
define f(l, r) as the sum of the squares of every integer from 1 to M if it exists on the visible side
of any card numbered from l to r. Given that Birzhan can flip any number of cards any number of
times, find and print the maximum value of f(l, r).

For example, given 3 cards and m = 5 we have the as follows:-

Now, for l = 1 and r = 2. We have 1, 2, 4, 5 on the two cards, the sum of their squares is 46. If
we flip the first card, we get 3, 4, 5, the sum of their squares is 50. And, if we flip both cards, we
get 1, 2, 3, 4, 5, the sum of their squares is 55. Hence, the maximum value of f(1, 2) in the
above case is 55.
Input
The first line contains three space-separated integers N, M, and Q, denoting the number of
cards, what numbers written on each card, and the number of queries, respectively. Each of the
next N lines describes the cards. On each line, the first number is 𝑋𝑖, denoting the count of
𝑡ℎ
numbers written on the visible side of the 𝑖 card. Next space-separated unique integers
represent the numbers written on the visible side of that card, each between 1 and M .

Next Q lines contain two space-separated integers, l and r, describing the query mentioned
above.

Output
Print the maximum value of f(l, r) for each query.

Constraints
6
● 1 ≤ 𝑁 * 𝑀, 𝑄 ≤ 10
● 1≤𝑙≤𝑟≤𝑁
● 0 ≤ 𝑋𝑖 ≤ 𝑀

Subtasks
1. [30 points] 1 ≤ 𝑀, 𝑄 ≤ 10
2. [70 points] No additional constraints

Example
Input

Output
Explanation

In the first query, there is only 1 card, and Birzhan has 2 options:

2 2
● Let it be as it is: sum of squares would be 1 + 2 = 5.
2
● Or flip it: sum of squares would be 3 = 9

So the maximum f(1, 1) Birzhan can achieve is 9.

On the second query, Birzhan doesn't need to flip any of them to maximize f(1, 2) so the answer
2 2 2
would be 1 + 2 + 3 = 14.

You might also like