Pascal Meets Boole

시간 제한1초메모리 제한2048 MB

요약
16가지 불 함수 중 하나로 만든 파스칼 모양 삼각형에서 r번째 행 i번째 비트를 구하거나, 처음 r개 행에 있는 1의 개수를 센다.
난이도

보통10점 중 7점

유형
비트 연산, 수학, 조합론
정답자
아직 제출이 없습니다

문제

Many people are familiar with Pascal's Triangle, a triangular arrangement of integers named after the French mathematician and philosopher Blaise Pascal (1623--1662). If we number the rows of Pascal's Triangle 1,2,3,…,1, 2, 3, \ldots, starting from the top, then row rr contains rr elements, which we will number 1,2,…,r1, 2, \ldots, r from left to right. The 11st and rrth elements in row rr are set equal to 11, and for r≥3r \geq 3 and 1<i<r1 < i < r, element ii in row rr is the sum of elements i−1i-1 and ii in row r−1.r-1. More informally, each "non-edge" element is the sum of the two elements immediately above it. Figure J.1(a) depicts the first 88 rows of Pascal's Triangle.

Figure J.1: (a) Pascal’s Triangle, (b) Pascal-Boole triangle for function 10001000

But what if we consider a rule other than standard addition for combining values? Since the edge elements are bits 11's), a natural option is to use any two-input Boolean function, named after the English mathematician and philosopher George Boole (1815--1864). For example, the Boolean function given by the following truth table generates the triangle depicted in Figure J.1(b) (where we also show the first 88 rows). In this truth table, xx and yy correspond to elements i−1i-1 and i,i, respectively, in row r−1r-1, and f(x,y)f(x,y) is the resulting element ii in row rr.

xxyyf(x,y)f(x,y)
000011
001100
110000
111100

In general, if we label the bits in the rightmost column of any such truth table b_00,b_01,b_10,b_11b\_{00}, b\_{01}, b\_{10}, b\_{11} from top to bottom, then we can compactly represent a two-input Boolean function by the 44-bit string b_00b_01b_10b_11.b\_{00} b\_{01} b\_{10} b\_{11}. So the example function above is represented by 10001000.

Your challenge is to answer two kinds of questions about "Pascal-Boole" triangles:

  1. For a given Boolean function, f,f, what is the bit in row rr, position ii?
  2. For a given Boolean function, f,f, how many 11's are there in the first rr rows?

입력

The first line of input contains an integer, nn (1≤n≤250),(1 \leq n \leq 250), the number of test cases. This is followed by nn lines, each of which has one of two forms:

  • ff B rr ii
  • ff N rr

In both cases, f is a 44-bit binary string representing a two-input Boolean function, and rr is an integer (1≤r≤106).(1 \leq r \leq 10^6). In the first case, ii is an integer (1≤i≤r).(1 \leq i \leq r).

출력

For a test case of the form ff B rr ii, output a line containing the bit in row rr, position ii of the Pascal-Boole triangle generated using ff. For a test case of the form ff N rr, output a line containing the number of 11's in the first rr rows of the Pascal-Boole triangle generated using ff.

예제1

  1. 예제 1

    입력
    3
    1000 B 5 3
    1111 N 7
    0100 B 6 4
    
    예상 출력
    1
    28
    0