Under construction

Still being built. Things may change

Aquarelle

Time limit0.4sMemory limit1024 MB

Summary
Given color sets for N cells and an initial painted range l to r, decide if the rest can be painted so each new cell adds an unseen color.
Level

Hard8 of 10

Topics
Dynamic programming, Intervals, Hash map
Solved
No attempts yet

Problem

Marincho loves to paint with watercolors. He wants to make a color sequence of NN cells. For each cell ii (1≤i≤N1 \le i \le N), he picks a set of colors AiA_i of size KiK_i, mixes them, and paints the cell with the result.

He has already painted cells ll through rr using Al,Al+1,…,ArA_l, A_{l+1}, \dots, A_r. He now paints the remaining cells in a fixed order. The next cell to paint is cell l−1l-1 or r+1r+1, whichever exists. If the painted cells are LL through RR, the next cell is:

  • If L=1L = 1 and R=NR = N, all cells are painted.
  • If L=1L = 1 and R<NR < N, the next cell is R+1R+1.
  • If L>1L > 1 and R=NR = N, the next cell is L−1L-1.
  • If L>1L > 1 and R<NR < N, the next cell is L−1L-1 or R+1R+1.

After painting cells ll through rr, Marincho finds the sequence too monochromatic. Every cell he paints from now on must contain at least one new color, one that appears in no cell painted so far. Write a program aquarelle that determines whether the remaining cells can all be painted. Answer this for each of the QQ initial paintings.

Input

The first line contains NN. Each of the next NN lines contains KiK_i followed by the colors c1 c2… cKic_1 \ c_2 \dots \ c_{K_i}, which are distinct positive integers. The next line contains QQ. Each of the last QQ lines contains ll and rr. Numbers on a line are separated by one space.

  • 1≤N≤5×1051 \leq N \leq 5 \times 10^5
  • 1≤Ki≤1.2×1061 \leq K_i \leq 1.2 \times 10^6, K1+K2+⋯+KN≤1.2×106K_1 + K_2 + \dots + K_N \leq 1.2 \times 10^6
  • 1≤cj≤1061 \leq c_j \leq 10^6
  • 1≤l≤r≤N1 \le l \le r \le N
  • 1≤Q≤51 \leq Q \leq 5

Output

For each initial painting, in input order, print 1 if the remaining cells can be painted, otherwise print 0.

Hint

Let us analyze the first initial painting. An optimal order is shown in the table below.

Painted cellsRemaining cellsNext cell
3,43, 43,4,5,63, 4, 5, 6Cell 2.
2,3,42, 3, 43,5,63, 5, 6Cell 5.
2,3,4,52, 3, 4, 55,65, 6Cell 1.
1,2,3,4,51, 2, 3, 4, 566Cell 6.
1,2,3,4,5,61, 2, 3, 4, 5, 6noneAll cells are painted successfully.

Note that if cell 5 were painted first, the painting could not be completed.

Let us analyze the third initial painting.

Painted cellsRemaining cellsNext cell
551,2,5,61, 2, 5, 6Cell 4.
4,54, 51,5,61, 5, 6Cell 3.
3,4,53, 4, 55,65, 6Cell 6.
3,4,5,63, 4, 5, 655No further cell can be painted.

Note that if cell 6 were painted first, the later steps would be the same and the painting would still fail. The answer here is 0.

Examples1

  1. Example 1

    Input
    6
    2 5 3
    1 4
    1 1
    1 2
    2 3 4
    1 6
    3
    3 4
    2 3
    5 5
    
    Expected output
    1
    1
    0