Somewhere in Andromeda, (yeah our neighbor galaxy!) Mystery Land, is having some signs of life. We just have found stairs there. But with different heights of each step.
Pictorially the stairs are like this:
The width of each step is same W, but for each stair numbered 'i', the total height of block of with W used for making the step is not uniform.
They used two functions for height Y[x] of each step number x.
Sam, being not very good pilot (but an awesome mathematician), was getting bored in his lab, now he wonders if these stairs are to be covered with some royal carpet, what would be the required length of the stair-carpet! (The red part shown in the image!)
Now you will we given and array A of function number to be used for ith step. With A[i]=1 or 2. Depending on that value, height of ith step will be calculated.
Input:
First line containing T, the number of test cases.
Then T test cases are as follows:
code
First line containing two Integers W, the width of steps and N, the number of steps.
Next line containing N space separated integers A[1], A[2]...., A[N].
Output:
code
For each case, print the total length of carpet needed to cover the stairs, on a newline.
Constraints:
1 ≤ W ≤ 1000000000
1 ≤ N ≤ 100000
1 ≤ T ≤ 100
SAMPLE INPUT
4
2 2
1 1
2 2
2 2
2 2
1 2
2 2
2 1
SAMPLE OUTPUT
8
6
7
8
Explanation
For case 1:
W = 2, N = 2
A[] = {1, 1}
So, for covering step one, it will take 2 + 21 = 4 units and for step no. 2 again, the vertical length to be covered, will be Y[2] - Y[1] = 22 - 2*1 ,and width W is also needed, so it's 2+2 = 4. So total length needed is 8.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We are given a problem about stairs. There are steps, each step has width W (same for all). The height of each step (the vertical rise from the previous step to the current step) is determined by a function based on step number x (starting from 1). But careful: The description: "height Y[x] of each step number x." Two functions:
Y[x] = 2*x
Y[x] = Y[x-1] + 1
with Y[0] = 0.
But wait: The second function is defined recursively: Y[x] = Y[x-1] + 1. That means it's essentially Y[x] = x (since Y[0]=0, Y[1]=1, Y[2]=2, ...). So function 2 gives Y[x] = x.
But note that the step height from step i-1 to step i is not directly Y[i]; Y[i] is the total height of the block? Need to interpret.
Let's read the picture description: "Pictorially the stairs are like this: The width of each step is same W, but for each stair numbered 'i', the total height of block of with W used for making the step is not uniform. They used two functions for height Y[x] of each step number x."
From typical staircase: A step consists of a horizontal tread (width) and a vertical riser (height). Usually, each step has a rise (vertical) and a run (horizontal). In this problem, the width W is the horizontal run of each step. The vertical part is the rise? But the description says "the total height of block of with W used for making the step is not uniform." Could be that each step is like a rectangular block of width W and height Y[x]? That seems odd because steps are usually incremental: the first step goes from ground to height Y[1]; the second step goes from Y[1] to Y[2]; etc. That matches typical stair: the height of the i-th step from the floor is cumulative.
I think Y[x] represents the total height from the floor to the top of step x. That would be consistent: Y[0] = 0 (floor), then step 1 raises to height Y[1]; step 2 raises to height Y[2]; and so on. The vertical part of step i is the difference Y[i] - Y[i-1] (the riser). The horizontal part is the tread width W. The carpet likely runs along the profile of the stairs (the red line in typical stair-carpet problems). Typically, to cover stairs with carpet that lies flush on the tread and riser, the length of carpet needed is sum of the hypotenuse? Wait, but the sample calculation: For case 1: W=2, N=2, A = {1,1}. Then they computed: for covering step one, it will take 2 + 21 = 4 units and for step no. 2 again, the vertical length to be covered, will be Y[2] - Y[1] = 22 - 2*1 ,and width W is also needed, so it's 2+2 = 4. So total length needed is 8.
They computed per step: for step 1: 2 + 21 = 4. That's W + something? 21 is Y[1]? Since Y[1] = 21 = 2? But they wrote 21=2, but they added W=2 to get 4. Actually they said "2 + 21 = 4". That suggests the length for step 1 is W + Y[1]? But Y[1] for function 1 is 21 = 2. So length for step 1 = W + Y[1] = 2+2=4. For step 2: they computed "vertical length to be covered, will be Y[2] - Y[1] = 22 - 21 ,and width W is also needed, so it's 2+2 = 4." So step 2 length = W + (Y[2]-Y[1]) = 2 + (4-2) = 2+2=4.
Thus total length = sum over steps of (W + (Y[i] - Y[i-1]) )? But that would be NW + sum of riser heights = NW + Y[N] - Y[0] = NW + Y[N]. But check: For case 1, N=2, W=2, Y[2] = 4, so NW + Y[N] = 4+4=8, matches.
But wait: they computed step 1 as W + Y[1]? That would be W + (Y[1]-0) = W + riser of step1. So indeed per step i, length = W + (Y[i] - Y[i-1]). That sum over i=1..N = NW + Y[N] - Y[0] = NW + Y[N]. So the total carpet length is NW + Y[N] (since Y[0]=0). So it's simply that: sum of risers plus sum of treads? But wait, why is the carpet length exactly the sum of risers plus treads? Usually, if you lay a carpet on each step covering the tread and riser, the carpet length required for each step is the length of the diagonal? Actually if you put a carpet on top of the step (the horizontal tread) and then go up the vertical riser, the carpet would be bent at the edge; the length along the carpet (if it's a continuous strip) is the sum of the horizontal and vertical lengths for each step (if the carpet is laid flat on the tread and then goes up the riser, but it's one continuous piece; the carpet follows the profile, so its total length is the sum of the tread lengths plus the sum of the riser heights. Yes, that's typical: the length of carpet needed to cover stairs is the sum of the run plus the rise for each step. So that matches: For each step, carpet covers the width W (horizontal) and the riser height (vertical). So total length = NW + total rise = N*W + Y[N].
But is that correct? In the example, they computed per step: W + (Y[i]-Y[i-1]) = W + riser. And total = NW + Y[N] = NW + total height.
Now let's verify other sample cases.
Case 2: Input: 2 2; A = {2,2}. So function 2: Y[x] = x. So Y[1]=1, Y[2]=2. Then NW + Y[2] = 22 + 2 = 4+2=6. Sample output is 6. Good.
Case 3: Input: 2 2; A = {1,2}. So step1 uses function 1? Wait we have array A[i] which is function number for ith step. But careful: The description: "you will be given an array A of function number to be used for ith step. With A[i]=1 or 2. Depending on that value, height of ith step will be calculated." So for each step i, the function determines Y[i]? Possibly Y[i] is computed based on the chosen function for that step. But there is ambiguity: Does A[i] determine how to compute Y[i] from previous? Because function 2 is defined recursively: Y[x] = Y[x-1] + 1. That uses previous Y. But if we have mixed functions, we need to know the order: we compute Y[0]=0. Then for i from 1 to N, we set Y[i] according to function A[i]. So Y[i] = if A[i]==1: 2i; else: Y[i-1] + 1. But careful: Function 1 doesn't depend on previous, it's an absolute formula: 2x. So Y[i] = 2*i. But does that depend on i? Yes.
But note that function 1 might produce a height that is not necessarily greater than previous Y[i-1]? It should be, because stairs go upward. But if we mix, could Y[i] be less than Y[i-1]? Let's check: If A[i]=1, Y[i]=2i. Since i increments, 2i > 2*(i-1) if previous step also used function1? But what if previous step used function2 and gave Y[i-1] = (i-1) (or maybe some value) then Y[i] = 2i could be much larger, that's fine. But could it be smaller? 2i is always > (i-1) for i>=1, so it's larger. So ok.
Now case 3: A = [1,2]. i=1: A[1]=1 => Y[1] = 21=2. i=2: A[2]=2 => Y[2] = Y[1] + 1 = 2+1=3. Then total length = NW + Y[N] = 2*2 + 3 = 4+3=7. Sample output is 7. Good.
Case 4: A = [2,1]. i=1: A[1]=2 => Y[1] = Y[0] + 1 = 0+1=1. i=2: A[2]=1 => Y[2] = 22=4. Then total = 22 + 4 = 4+4=8. Sample output is 8. Good.
So indeed the total carpet length = N * W + Y[N], where Y[N] is computed iteratively as described.
Therefore the problem reduces to: given W, N, and an array A[1..N] of 1 or 2, compute Y[N] according to the recurrence: Y[0] = 0; for i from 1 to N: if A[i] == 1: Y[i] = 2 * i; else if A[i] == 2: Y[i] = Y[i-1] + 1.
We need to output N*W + Y[N] for each test case.
Constraints: N up to 100k, T up to 100. So total N across test cases could be up to 10^7 (100 * 100k = 10^7). That is manageable for O(N) per test case, but we might want to be efficient. However O(N) per test case is fine. But note that W can be up to 1e9, N up to 1e5, so N*W can be up to 1e14, which fits in 64-bit (2^63-1 ~9e18). So use 64-bit (long long in C++).
Thus the solution is straightforward: read T, then for each test case, read W, N, then read N ints for A. Compute Y = 0; loop i=1..N: if A[i]==1: Y = 2i; else if A[i]==2: Y = Y + 1; (but careful: for function 1, the formula uses i, not previous Y, so set Y = 2i). Then answer = N * W + Y. Print.
But wait: The formula for function 1 is Y[x] = 2x. But in the description, x is step number. So yes Y = 2i.
However, there is a nuance: The step numbers start from 1. So i is the step number. So it's fine.
But what about function 2: Y[x] = Y[x-1] + 1. That's also straightforward.
Now is there any tricky situation where we need to consider that the function may be applied to previous step? No.
Thus answer is computed as described.
But wait, we must ensure that for function 1, it's 2*i regardless of previous Y? Yes.
Now let's double-check sample: For case 1: Y[1]=2, Y[2]=4 => Y[2]=4. So NW = 22=4, plus 4 =8. Case 2: Y[1]=1, Y[2]=2 => total =4+2=6. Case3: Y[1]=2, Y[2]=3 => total=4+3=7. Case4: Y[1]=1, Y[2]=4 => total=4+4=8. Yes.
Thus the solution is trivial.
However, the problem might be intended to be more complex? Let's read the problem statement fully (the one provided). It says:
"Sam, being not very good pilot (but an awesome mathematician), was getting bored in his lab, now he wonders if these stairs are to be covered with some royal carpet, what would be the required length of the stair-carpet! (The red part shown in the image!)
Now you will we given and array A of function number to be used for ith step. With A[i]=1 or 2. Depending on that value, height of ith step will be calculated."
That's it.
Now the constraints and sample match the simple interpretation.
But perhaps we need to consider that the carpet length might be the sum of the lengths of the hypotenuse of each step? That would be sqrt(W^2 + (riser)^2) per step. But the sample uses W + riser, not sqrt. So clearly it's additive.
Wait: In the sample explanation, they said: "for covering step one, it will take 2 + 2*1 = 4 units". That's W + Y[1]? But Y[1] is 2, which is the riser height from floor to step1. So they added the riser and the tread. So indeed it's linear addition, not hypotenuse. So it's the total length of carpet needed if the carpet is cut to match the profile, but laid flat, the length along the carpet is the sum of horizontal and vertical segments? Actually if you have a carpet that goes over the tread and the riser, you'd need to go up the riser, which is vertical, so the carpet must have length equal to the sum of tread and riser for each step if it's a continuous piece? Actually imagine a carpet that covers each step: you go horizontally across the tread (length W), then you go up the riser (height h). The carpet is a continuous strip that goes up the stairs. If the carpet is flexible and goes around the corner, the total length of carpet used is indeed the sum of the tread lengths plus the sum of the riser heights, because the carpet lies flat on each part; the length along the carpet is the sum of the lengths of each segment. It's not the hypotenuse because the carpet is not stretched diagonally; it's laid on the step shape. So it's correct.
Thus the solution is simple: simulate.
But wait, there is a twist: The problem might be that the carpet covers the top of each step and the vertical front? In typical stair carpet measurement, it's the sum of the tread and riser for each step. Yes.
Now we should consider if there's any alternative interpretation: Could Y[x] represent the height of the block of the step (so step x is a rectangular block of height Y[x] placed on top of previous steps)? Then the total vertical rise to step x is sum of block heights? That would be different. But the given explanation shows that for step 1, the carpet length includes Y[1] (2) plus W. And for step 2, they used Y[2] - Y[1] as the vertical part. So indeed Y is cumulative.
Thus we are good.
Now we should produce code that reads input, computes as described.
But note: N can be up to 100k and T up to 100. The total input size can be up to 10 million numbers. Use fast I/O.
Now we must be careful: The input format: First line T. Then each test case: first line: W and N. Then next line: N space separated integers A[1]..A[N]. So we read that.
Edge Cases: What if function 2 is used for first step? Then Y[1] = Y[0] + 1 = 1. That's fine.
Now might there be any possibility of overflow when computing 2i? i up to 1e5, so 2i up to 2e5, well within 64-bit. Y[N] could be at most? If all steps use function 1, Y[N] = 2N, which is 2e5. But what if function 2 is used repeatedly? Y[N] = N (since each step adds 1). So Y[N] max 2N = 200k. Actually could there be a larger possibility if function 1 gives 2i, which can be bigger than previous Y, but then subsequent function 2 adds 1, so max Y[N] is 2N? Let's simulate worst-case: Suppose all steps use function 1? Then Y[N] = 2N. If some earlier steps use function 2, Y might be lower. So max is 2N, which is at most 2e5. So Y[N] is small. However NW can be huge: N up to 1e5, W up to 1e9, so NW up to 1e14. So we need 64-bit.
Thus answer = N * W + Y[N]. We'll compute using long long.
Now is there any trick? Possibly they want to compute Y[N] without simulating all steps? But it's easy to simulate. However maybe the constraints actually might be higher? The problem statement says N ≤ 100000, T ≤ 100. Simulation is O(N) per test case, total up to 10 million operations, which is fine in any language.
But we must read the input correctly. The sample input includes 4 test cases with N=2 each. So we can test.
Let's double-check: In sample case 3: 2 2 and then line "1 2". That's third test case? Actually sample input:
4
2 2
1 1
2 2
2 2
2 2
1 2
2 2
2 1
There are 4 test cases, each with W=2, N=2, but they are separated like:
1st test case: first line "2 2", next line "1 1"
2nd test case: first line "2 2", next line "2 2"
3rd test case: first line "2 2", next line "1 2"
4th test case: first line "2 2", next line "2 1"
Yes.
So implementation: For each test case, read W and N, then read N integers. Could be that the next line might have less numbers? But per spec, it's exactly N numbers.
Now code.
But wait, is there any hidden nuance about Y[i] when A[i]=1: The function is Y[x] = 2*x. But what is x? It says step number. So yes it's i.
But what if step numbers start at 0? They said Y[0]=0. So first step is i=1.
Thus implementation straightforward.
But let's consider if there is any requirement to output modulo something? No, just print integer.
Thus solution: O(N) per test case.
Let's produce a Python solution (since the problem might be from some contest, we can use Python). Use sys.stdin.read() for fast input. Parse integers.
Implementation steps:
Read all ints via sys.stdin.buffer.read().split() into list of ints.
Use iterator.
first integer: T.
For each test case: read W, N; then read N integers for A.
Initialize y = 0.
For i in range(1, N+1): a = A[i-1]; if a == 1: y = 2*i; else: y = y + 1.
Compute ans = N * W + y.
Print ans.
But careful: For function 2, we do y += 1 (since y is Y[i-1] then we assign Y[i] = Y[i-1]+1). That's fine.
Now verify: For case with mixed functions: For i=2 and a=2, y currently holds Y[1] so y+1 = Y[2]. Good.
Now, check for large N: loops fine.
One might wonder: is there any scenario where A[i]=1 but we need to compute Y[i] = 2i, but this might be less than Y[i-1]+1? Possibly not, but anyway we set it to 2i. So the recurrence is not dependent on previous Y; we overwrite it.
Thus correct.
But wait, what if the function 1 is Y[x] = 2*x, but x is the step number, not the index i? That's consistent.
Now what about the possibility that the function for step i could be applied to compute Y[i] using not just the step number but maybe also previous Y? No.
So the problem is extremely simple.
But maybe there is a twist: The array A gives function number for ith step, but maybe the function used for step i determines the height of that step block (the vertical part) rather than the cumulative height. However the sample explanation clearly uses cumulative. They said: "height of 0th step, floor, Y[0] = 0." So Y[x] is the height of step x from floor. So it's cumulative.
Thus answer is N*W + Y[N].
Now, because this is so simple, maybe there is a trick: The carpet length might be the sum of the lengths of the diagonal plus something else? But no.
We could also derive Y[N] in closed form: For each i where A[i]=1, it resets Y to 2i; subsequent 2s add 1 each. So Y[N] depends on last occurrence of 1? Let's think: Starting from i=1, we track Y. If we see a 1 at position i, Y becomes 2i. Then subsequent 2's increase by 1 each. So Y at any point = 2 * i_last1 + (current_index - i_last1) if i_last1 is the most recent index where A[i]=1, and if there was a 1 at that position; if never 1, then Y = i (since all 2's, Y = i because each adds 1 from Y[0]=0, so Y[i] = i). So Y[N] can be computed by scanning, but scanning is fine.
But maybe we can compute more efficiently with prefix sums? Not needed.
Given that the constraints are moderate, we just simulate.
Now, is there any catch about integer overflow in Python? Python ints arbitrary precision, so fine.
But wait, the sample input appears to have lines: "2 2" repeated many times. But that's fine.
Now produce final solution.
But before finalizing, let's double-check the problem statement to ensure no misinterpretation: "Pictorially the stairs are like this: The width of each step is same W, but for each stair numbered 'i', the total height of block of with W used for making the step is not uniform. They used two functions for height Y[x] of each step number x." The phrase "total height of block of with W used for making the step" could be interpreted as each step is a rectangular block of width W and height Y[i] placed on top of the previous steps? That would be cumulative? Actually if you place a block of height Y[i] on top of previous step, then the total height from floor becomes sum of Y[1] + Y[2] + ...? But they set Y[0]=0, and for each step x they define Y[x] via functions. And the sample explanation treats Y[2]-Y[1] as the vertical part for step 2. So Y is cumulative. So that's settled.
Now, is there any requirement to consider that the carpet might also cover the top of the last step? Possibly yes, that's included: For step N, we include W + (Y[N] - Y[N-1]). And that sum yields N*W + Y[N]. So yes.
Thus answer is correct.
Now, think about large T and N. In Python, 10 million iterations might be near time limit if not optimized? Typically 10 million loops in Python is okay (about 0.3-0.5 seconds? Actually Python loops are slower: ~50 million ops per second? No, Python loops do about 50 million simple operations per second? Actually Python loops are slower, around 50 million per second for very simple loops in PyPy? Let's estimate: In CPython, a simple loop with arithmetic might be ~20-30 million per second? Actually typical speed: around 50-100 million operations per second for C, but Python is slower: ~10 million simple loop iterations per second maybe. 10 million could be ~1 sec in CPython, but with PyPy might be faster. Many judges allow Python with optimizations. But T up to 100, N up to 100k each, max total N = 10 million. That's okay for Python if we use efficient input (sys.stdin.buffer.read) and avoid overhead per test case. It should pass within typical time limit of 2 seconds? Possibly borderline, but we can optimize a bit: since Y[N] can be computed by scanning A and using the recurrence, that is O(N). Could we compute Y[N] faster using knowledge of last occurrence of 1? For each test case, we could compute number of consecutive 2's after last 1 etc. But scanning is fine. We'll do scanning.
Alternatively, we can process using Python's list operations: compute Y by iterating. Could also use accumulate but it's custom.
We can also compute Y[N] without simulating each step: find the last index where A[i]==1, say last1. Then Y[N] = 2last1 + (N - last1) if last1 exists; else Y[N] = N. But careful: If there is a 1 after that? last1 is the last index with 1, so that's correct: because after a 1 at position p, Y[p] = 2p; then each subsequent step (p+1 ... N) if they are 2, will increment by 1 each. However, if there is a 1 later, it resets to 2i. So final Y[N] = 2 * (last index of 1) + (N - last_index_of_1) if A[N] is not 1? Actually if the last index itself is a 1, then after that step, Y[last1] = 2last1, and then for steps after last1 (if any), each step is 2, they add 1. So final Y[N] = 2last1 + (N - last1). But what if there are 1's after last1? That's impossible because last1 is the last one. So yes. But if there are steps after last1 that are 1? No. So this formula holds if last1 exists. If no 1, then Y[N] = N. However, what if there are 1's before last1 but also 2's, the effect is overwritten by later 1, so only the last 1 matters. Indeed, because whenever we hit a 1, Y is set to 2*i, discarding previous Y. Then subsequent increments add 1. So final Y depends only on the last occurrence of 1 (if any). That is a crucial observation. Let's verify with cases:
Case4: A=[2,1], last1 = index 2 (i=2). Then Y[2] = 22 + (2-2) = 4. matches.
Case3: A=[1,2], last1=1 => Y[2] = 21 + (2-1)=2+1=3.
Case2: A=[2,2], no 1 => Y[2] = 2? Actually no 1, Y = N = 2. matches.
Case1: A=[1,1], last1=2 => Y[2] = 2*2 + (2-2)=4. matches.
So indeed we can compute Y[N] in O(N) by scanning to find last index of 1, or even in O(N) by scanning all but still need to read array. But we can avoid storing the entire array? Since we only need last index of 1 and also need to count N? Actually we could read the N numbers and track last1 index (where value==1). But we still have to read them; we can process them as we read, without storing the whole list. That's efficient. So algorithm: for each test case, read W, N, then loop i=1..N reading integers a; if a == 1, set last1 = i. After reading all, if last1 exists: Y = 2last1 + (N - last1); else Y = N. Then answer = NW + Y.
But is this always correct? Let's test with more complex sequences, e.g., A = [2,1,2,2]. N=4. According to recurrence: i=1: Y=1; i=2: a=1 => Y=4; i=3: a=2 => Y=5; i=4: a=2 => Y=6. So Y[4]=6. Our formula: last1 = 2 => Y = 22 + (4-2) = 4+2=6. Yes. What about A = [1,2,1,2]. N=4: Simulate: i=1: Y=2; i=2: a=2 => Y=3; i=3: a=1 => Y=6; i=4: a=2 => Y=7. Y=7. last1 = 3 => Y = 23 + (4-3)=6+1=7. Good. What about A = [2,2,2,1]? N=4: Simulate: i=1: Y=1; i=2: Y=2; i=3: Y=3; i=4: a=1 => Y=8. last1 = 4 => Y = 2*4 + (4-4) = 8. Good. So indeed the final Y depends only on the last 1 (if any). Also if there is no 1, Y=N.
Thus we can compute Y[N] without simulating all steps. But we still need to iterate over all N inputs to find last1. That's O(N) anyway. So we could just simulate while reading, but it's simpler to just track last1. However, we must be careful: When we simulate, we also need to account for Y[N] if we use incremental updates, but that's also O(N). The advantage of last1 method is that we don't need to maintain a running Y value, but that's minor. Either is fine.
But wait: The recurrence for function 2 is Y[i] = Y[i-1] + 1. But what about function 1? It sets Y[i] = 2i. This does not depend on previous Y. So yes, the effect of earlier steps is overwritten by later 1's. So final Y[N] is determined solely by the last occurrence of 1 (or none). This is true because after a 1, the value is exactly 2i, and subsequent 2's add exactly the number of steps after. Even if there is a later 1, it overwrites again. So last 1 is sufficient.
Thus we can compute Y[N] quickly: if there is at least one 1, let p = index of last 1 (1-indexed). Then Y[N] = 2p + (N - p) = p + N? Actually 2p + (N-p) = p + N. Wait 2p + N - p = p + N. So Y[N] = N + p. That's even simpler! Let's check: For A=[1,1] -> p=2 => Y = 2+2=4? Actually N=2, p=2 => N+p=4, correct. For A=[1,2] -> p=1 => Y = 2+1=3, correct (N+p=2+1=3). For A=[2,1] -> p=2 => Y=2+2=4, correct. For A=[2,2] -> no 1, Y=N=2, which is N+0? Not exactly, but if we set p=0 (no 1), then N+p = N, that matches if we define p=0 for no 1. So we can set p = index of last 1, or 0 if none. Then Y[N] = N + p.
But wait, is this always true? Let's test: A = [1,2,1,2], N=4, p=3 => Y = N + p = 4+3=7, matches. A = [1,2,2,2], p=1 => Y = 4+1=5, but simulation earlier? Let's simulate: i=1: Y=2; i=2: a=2 -> Y=3; i=3: Y=4; i=4: Y=5. Yes Y=5, N+p=4+1=5. A = [2,2,2,1], p=4 => Y=4+4=8, matches. A = [2,1,2], N=3, p=2 => Y=3+2=5, simulation: i=1:1, i=2:1? Actually A[2]=1 => Y=4, i=3:2 => Y=5, yes.
But what about case where there are multiple 1's? Last one determines. So indeed Y[N] = N + p, where p is the index of the last 1 (1-indexed), and if no 1, p=0 gives Y=N.
But is that always? Let's prove: If last 1 occurs at index p, then Y[p] = 2p. Then for each subsequent step i from p+1 to N, we have A[i]=2 (since p is last 1). So each of those steps increments Y by 1. Number of such steps = N-p. So Y[N] = 2p + (N-p) = p + N. Yes. If there is no 1, then all steps are 2, so Y[1]=1, Y[2]=2,... Y[N]=N, which is N+0.
Thus Y[N] = N + (index of last 1, or 0 if none). That is extremely simple. So we don't even need to simulate; we just need to read the N numbers to find the last occurrence of 1. That's still O(N) but we don't need to compute Y incrementally. However we can also compute by scanning the array and just track the maximum i where A[i]==1.
Thus answer = N*W + (N + last_index_of_1) where last_index_of_1 is 0 if none.
But careful: In the case where there is a 1 at position i, then Y[N] = N + i? Let's test with sample: Case1: N=2, last1=2 => Y=2+2=4, N*W=4 => total=8. Works.
So the answer is W*N + N + last1_index.
But wait, is there any scenario where A[i] could be something else? Only 1 or 2.
Thus we can compute answer quickly: ans = N * (W + 1) + last1_index? Because NW + N + last1 = N(W+1) + last1. But that's just rearranging.
Now confirm: For case with no 1, last1=0, ans = NW + N = N(W+1). But earlier we had ans = NW + Y[N] and Y[N]=N, so ans = NW+N = N*(W+1). That matches. So for no 1, answer = N*(W+1). For case with last1 = p, answer = N*(W+1) + p? Wait: NW + (N+p) = N(W+1) + p. Yes.
But careful: In case with last1 = p, answer = N*(W+1) + p. Check case1: N=2,W=2 => N*(W+1)=2*3=6, +p=2 => 8. Yes. Case3: N=2,W=2 => 6 + p=1 => 7. Case4: 6 + p=2 => 8. Case2: no 1 => p=0 => 6. Good.
Thus we have a very simple formula.
Now we need to compute p = max{ i | A[i] == 1 } or 0 if none.
Thus we don't even need to track Y. This is more efficient, but still need to read the array to find the last index of 1. Could we avoid reading the entire array if we are given it? No, because we must process the input anyway. But we can read and discard each number after checking if it's 1. That's essentially the same as before.
Now, is there any possibility that the recurrence for function 1 is Y[x] = 2*x, but maybe the step number x is not the index i but the number of times function 1 has been used? No, based on sample and statement, it's step number.
Thus we are confident.
Now, implement solution: For each test case, read W, N. Then read N integers. Keep variable last_one = 0. For i from 1 to N, read a; if a == 1, set last_one = i. After reading all, compute ans = N * W + N + last_one. Or using 64-bit: ans = N * (W + 1) + last_one. But careful: W can be up to 1e9, N up to 1e5, so N*(W+1) fits in 64-bit.
But note: In languages with fixed integers, use long long.
Now, we must be careful: In the input, there might be multiple test cases, and we must read the numbers line by line. Using sys.stdin.buffer.read() to read all and parse ints is fine. Then we process sequentially.
Implementation details in Python:
def solve():
import sys
data = list(map(int, sys.stdin.buffer.read().split()))
it = iter(data)
t = next(it)
out = []
for _ in range(t):
W = next(it)
N = next(it)
last_one = 0
for i in range(1, N+1):
a = next(it)
if a == 1:
last_one = i
ans = N * W + N + last_one # or N*(W+1) + last_one
out.append(str(ans))
sys.stdout.write("\n".join(out))
Now test with sample.
But wait, sample input has 4 test cases with N=2 each. So our code should produce 8,6,7,8. Good.
But we need to be cautious about reading: The input after T might not be exactly as described; but it's standard.
Now, one more thought: Could there be any scenario where the function for step i is 1, but we need to use the step number x for that step, but maybe step number is not the index i but the number of steps? Actually step number is i. So it's fine.
Thus solution is straightforward.
But wait: The problem statement mentions "stair-carpet! (The red part shown in the image!)". Possibly the red part includes also the vertical rise of the first step from the floor and the top of the last step? In the sum we include those. So all good.
Now, final answer: implement solve() function.
Now, before concluding, I'd like to double-check if the problem expects exactly the sum of W + riser for each step. Could there be an additional horizontal part at the beginning or end? For instance, sometimes the carpet might also cover the floor before the first step or after the last step? But from the sample calculation, they only summed steps. So no.
Thus answer.
But the problem might be from some contest like Hackerearth or CodeChef, where they expect O(N) solution, but maybe they intend to use this simplified formula. However, they might also expect you to notice the simplification. But even if you simulate, it's fine.
Now, since this is a "solve the problem" instruction, we will produce a solution.
Now, I'll produce a final answer in the form of a Python script.
But we need to output for each test case on a newline.
Thus final solution.
Potential pitfalls: When reading large input, using sys.stdin.buffer.read() is efficient. But we must ensure we convert to ints properly. The data might have newlines, but split handles.
Now, we will write code.
But also consider that T up to 100, N up to 100k, so total ints = 1 (T) + for each test case: 2 + N = about 10 million ints. This list of ints might use a lot of memory if we read all at once: 10 million ints in Python is about 280 MB? Actually Python int objects are large (~28 bytes each). So 10 million ints would be ~280 MB, which may be too high. That's a problem! We need to be careful. The total number of integers can be up to sum (N+2) over test cases, which max is 100 * (100000+2) = 10,000,200 plus T. So about 10 million integers. In Python, storing that many ints as Python objects in a list could exceed memory limits (like 256 MB or 512 MB). Actually 10 million ints of small values: each Python int object is 28 bytes (on 64-bit). So 10 million * 28 = 280 MB. Plus list overhead (~8 bytes per element) maybe additional, so around 300+ MB. That could be too high. So we should not read all ints into a list at once; we should process streaming.
We can use sys.stdin.buffer.read() to read all bytes and then map to ints via map and iterator, but that still creates a list if we do list(map(int, ...)). Actually map returns an iterator, but if we do data = list(map(int, sys.stdin.buffer.read().split())), that creates a list of ints. That's what we want to avoid. Instead, we can use an iterator over the split strings without storing all ints: we can use sys.stdin.buffer.read().split() which returns a list of bytes strings. That also stores all tokens as bytes objects, each token is a small object. For 10 million tokens, that would also be huge: each bytes object overhead maybe 33 bytes plus the content (small). That's also large. So we need a streaming approach: read line by line and parse each line. Since N can be large (100k), reading each test case's line of N numbers may be long, but we can read the line and split, then iterate over those numbers. However, for a test case with N=100k, the line will contain 100k numbers, which is fine to read as a string and split into a list of strings; that's 100k strings, which is okay memory-wise (maybe a few MB). Over T test cases we process sequentially, so at any time we only hold one test case's numbers. That's acceptable.
Thus better approach: use sys.stdin.readline() to read line by line. Since N can be up to 100k, the line may be long but still within limits. Use .split() to get tokens.
But careful: The input lines may be broken across lines? Usually each test case's array is on a single line. It says "Next line containing N space separated integers". So we can read that line and split.
Thus we can implement as:
import sys
def solve():
input_data = sys.stdin
T = int(input_data.readline())
out_lines = []
for _ in range(T):
line = input_data.readline()
while line.strip() == '':
line = input_data.readline()
W, N = map(int, line.split())
# Now read array line; might need to handle case where array spans multiple lines? Usually one line.
arr_line = input_data.readline()
# But sometimes N large, the line might be broken? According to problem, it's one line.
# We'll read until we have N numbers.
nums = list(map(int, arr_line.split()))
# If len(nums) < N, we need to read more lines until we have N numbers. Safer to read until we have N.
while len(nums) < N:
nums += list(map(int, input_data.readline().split()))
# Now find last index of 1
last_one = 0
# iterate over nums with index starting at 1
for i, a in enumerate(nums, start=1):
if a == 1:
last_one = i
ans = N * (W + 1) + last_one
out_lines.append(str(ans))
sys.stdout.write("\n".join(out_lines))
But this approach still reads the entire array into a list nums of size N, which is fine (max 100k). Memory okay.
But we could also process while reading the numbers without storing all, but we need to read the line anyway. We can iterate over the split result directly without storing list? Actually we can process each token as we parse. But we also need to know the index. So we can do:
tokens = arr_line.split()
for idx, token in enumerate(tokens, start=1):
if int(token) == 1: last_one = idx
But if the array spans multiple lines, we need to continue reading. Simpler: use a loop that reads integers one by one from the input stream. We can use a generator that yields ints from sys.stdin.read().split() but that would read all tokens at once, causing memory issue. So better to read line by line and process tokens.
Since N is up to 100k per test case, storing the list is fine.
Thus the above is acceptable.
But we need to be careful about large T and large N: reading line by line and storing list of ints for each test case and then discarding after is fine. Total memory per test case ~ O(N). Since N max 100k, list of ints ~ 0.8 MB? Actually each Python int is ~28 bytes, so 100k ints => 2.8 MB. Plus list overhead ~0.8 MB? Actually list of 100k references: 8 bytes per reference => 0.8 MB. The ints themselves 2.8 MB => ~3.6 MB. That's fine. And we only have one at a time.
Thus the solution is fine.
Now, we can also use the simplified formula to compute answer. Or we could simulate but simulation also uses O(N) time. However, using the last_one method is slightly faster because we don't need to compute Y incrementally. But both are O(N). The last_one method might be a tiny bit faster because it's just checking equality and updating index, while simulation would involve an assignment each step. But it's fine.
But we must verify: Are there any cases where the function 1 might be interpreted differently? What if the step number x is not the index i but something else? The statement: "they used two functions for height Y[x] of each step number x." So step number x. So it's index.
Thus we are safe.
Now, final code.
But wait: The sample input includes 4 test cases with N=2. Our code with while len(nums)<N would be unnecessary but okay.
Edge Cases: N=1. Then if A[1]=1, last_one=1, ans = 1*(W+1)+1 = W+1+1=W+2? Actually NW + N + last_one = W + 1 + 1 = W+2. Let's check: Step 1: riser = Y[1] = 21 = 2, tread W, total = W+2. Good. If A[1]=2, last_one=0, ans = W+1. riser = Y[1] =1, total = W+1. Good.
All good.
Now, we need to handle possibly large T and large N but overall sum of N across test cases might be up to 10^7. The code with loops over N and using Python's list of ints may be borderline but likely okay if optimized. 10 million operations in Python (just simple comparisons) should be okay (~0.2-0.5 sec). But reading input and converting to ints may be heavier. However, typical online judges allow 2-3 seconds for Python, 10 million ints parsing might be near the limit but usually acceptable with PyPy. We can try to speed up by using sys.stdin.buffer.read() and iterating over ints as a generator without storing all at once, but we need to avoid memory blow. We can use a fast scanner like:
import sys
def ints():
for num in sys.stdin.buffer.read().split():
yield int(num)
But that still holds all tokens as bytes objects? Actually sys.stdin.buffer.read().split() returns a list of byte strings, which would hold all tokens in memory. That could be memory-heavy. But we can use a generator that reads line by line and yields ints from each line. That's better.
We can implement a custom fast input that reads line by line and yields ints:
def read_ints():
for line in sys.stdin.buffer:
for num in line.split():
yield int(num)
But then we have to handle the structure: T, then for each test case: W, N, then N ints. Using an iterator from this generator would work, and we wouldn't store all tokens at once. That's efficient.
Let's implement that:
import sys
def main():
import sys
data = sys.stdin.buffer
it = (int(x) for line in data for x in line.split())
# Actually the above comprehension is a generator that yields ints from all lines. But it will still read all lines? No, it's a generator that reads lines as we iterate, because "for line in data" iterates over lines lazily. So it's okay: it yields tokens as needed, without storing all.
# However, we need to call next(it) to get values.
t = next(it)
out = []
for _ in range(t):
W = next(it)
N = next(it)
last_one = 0
for i in range(1, N+1):
a = next(it)
if a == 1:
last_one = i
ans = N * (W + 1) + last_one
out.append(str(ans))
sys.stdout.write("\n".join(out))
But note: The generator expression "(int(x) for line in data for x in line.split())" will produce ints from all lines. However, the iteration over data (the file) will happen as we consume the generator. That should be fine and memory efficient. But we need to be careful: The generator will read lines and split them; it will not store the entire file. It yields ints one by one. This is a common pattern for fast input in Python without storing all tokens.
But there's a nuance: The generator expression itself is an iterator; when we call next(it), it will read the next line from data as needed. This is efficient.
However, we must ensure that we don't have any other uses of sys.stdin that conflict. That's fine.
Thus we can implement this way.
But there's also a more explicit way: use a function that reads all ints via sys.stdin.buffer.read().split() and then map to ints, but as argued, that may use too much memory. So better to use the generator.
Alternatively, we can use sys.stdin.buffer.readline in a loop. That's also fine.
Given the problem constraints, the simpler line-by-line approach might be enough. But we need to handle the case where the array line might be broken across multiple lines? Usually not, but sometimes judges may have line breaks for large N? The problem says "Next line containing N space separated integers". So it's one line. So we can rely on that. But to be safe, we could read until we have N ints, but that adds complexity.
I'll go with the generator approach because it automatically handles any whitespace and doesn't care about lines. It just reads ints sequentially. That's simplest and robust. And memory efficient.
Thus final solution:
import sys
def solve():
import sys
# Create generator that yields ints from input
def int_gen():
for line in sys.stdin.buffer:
for num in line.split():
yield int(num)
it = int_gen()
t = next(it)
out = []
for _ in range(t):
W = next(it)
N = next(it)
last_one = 0
for i in range(1, N+1):
a = next(it)
if a == 1:
last_one = i
ans = N * W + N + last_one # N*(W+1) + last_one
out.append(str(ans))
sys.stdout.write("\n".join(out))
if name == "main":
solve()
Test with sample.
Now, confirm that the generator works: When we call next(it) repeatedly, it reads lines from sys.stdin.buffer lazily. So if we read N ints, it will read as many lines as needed. Since the input format is consistent, it's fine.
Edge: There might be blank lines. The generator skips blank lines because line.split() on an empty line yields no numbers, so it just continues.
Thus it's robust.
Now, one more check: In case there are leading/trailing spaces, it's fine.
Now, we should consider large input: The generator reads line by line, but if the array is on a single line, that line may be very long (N up to 100k numbers). That's okay; reading a line with 100k numbers might be about 200KB-300KB, which is fine. The generator will read that line, split it into maybe 100k substrings, and yield ints one by one. That's okay.
Now, performance: The conversion to int for each token might be a bit heavy, but 10 million conversions is okay in PyPy/CPython. In CPython, it might take a couple seconds. But typically it's acceptable.
Alternatively, we could use map(int, line.split()) and extend a list, but that would create a list for each line. But generator does that as well: line.split() creates a list of byte strings for that line. That's necessary to split. For a line with 100k numbers, that's a list of 100k byte strings. That's okay, memory about maybe 2-3 MB. And then we iterate over them and convert to int. That's fine. The generator will hold that list temporarily for each line. Since we process test cases sequentially, it's fine.
Thus the solution should pass.
Now, we can also use the formula: ans = N * (W + 1) + last_one.
But note: In the no-1 case, last_one = 0, ans = N*(W+1). That's correct.
Now, confirm with sample: Done.
Thus answer.
Now, maybe the problem expects to simulate Y because they didn't think about the simplification. But it's fine.
Now, I'll produce the final answer.
But before final, check if any possible off-by-one: For i starting at 1, last_one is set to i when a == 1. So if the last occurrence is at index N, last_one = N, ans = NW + N + N = NW + 2N. But NW + N + last_one = NW + N + N = NW + 2N. That matches formula N+p+N? Actually Y[N] = N + p, ans = NW + N + p. So if p=N, ans = NW + N + N = NW + 2N. In simulation, Y[N]=2N, so ans = N*W + 2N. Yes.
Now, check if last_one can be 0 (no 1). Then ans = NW + N. Simulation: Y[N] = N, so ans = NW + N. Good.
Thus correct.
Now, we also consider if there is any scenario where function 2 could be defined as Y[x] = Y[x-1] + 1, but maybe they use the function number for each step to compute the height of that step's block, not cumulative. But the sample explanation explicitly uses cumulative. So it's fine.
Thus final solution is ready.
Now, produce final answer in the response. ```python
import sys
def solve() -> None:
# Fast input: generator yielding integers from standard input
def int_gen():
for line in sys.stdin.buffer:
for num in line.split():
yield int(num)
code
it = int_gen()
t = next(it)
out_lines = []
for _ in range(t):
W = next(it)
N = next(it)
last_one = 0 # index of the last occurrence of function 1 (0 if none)
for i in range(1, N + 1):
a = next(it)
if a == 1:
last_one = i
# total length = N*W + (N + last_one) = N*(W+1) + last_one
ans = N * (W + 1) + last_one
out_lines.append(str(ans))
sys.stdout.write("\n".join(out_lines))