We need to solve a problem: given a string of # and ., representing floorboards (#) and missing floorboards (.), starting at position 0 (Polly's house) and ending at last position (last char) which is '#', we have to compute the number of days needed to cross, under the described process.
The process: they start with jump capacity L0 = 1 (they can jump any distance ≤ L0). They traverse from left to right. At each step, they can see the next floorboard? Actually "they are able to sense only how much they need to jump at that point, and have no idea of the further reaches of the passage till they reach there. That is, they are able to only see how far ahead is the next floorboard." So they stand on a floorboard (position i) and look ahead; they see the distance to the next floorboard. If that distance d (the number of '.'s until next '#', plus maybe 1? Let's formalize.
Given the string P of length n, indices 0..n-1, with P[0]='#', P[n-1]='#'. The characters represent the boards: '#' means present, '.' means missing. To cross, they need to go from position 0 to position n-1, stepping only on '#' positions. They start on # at index 0. At each step, they can jump from current position i (a '#') to some future position j>i (a '#') such that the distance between positions? But careful: The passage is linear, presumably they can jump over missing boards. The description: "some of the floorboards are missing, and that taking a step forward would have them plummet to their deaths below." That suggests they cannot step on missing boards. They must land on floorboards. They can jump over gaps. They can jump any length ≤ current max jump L. Initially L=1. They can jump exactly 1? "they start by being able to 'jump' a length of 1." Means they can jump exactly 1 unit? But also "once they have mastered jumping a particular length L, they are able to jump any amount less than equal to L as well." So they have a max capability L. They can choose to jump less.
They traverse from leftmost # to rightmost #. At each point, they only know the immediate gap ahead? The process: They start from Polly's house (leftmost) and walk along the passage to Digory's. They "walk" but when they encounter missing floorboards, they need to jump. Actually they are walking along the boards; if they see a missing board, they need to jump. But the phrasing: "they start from Polly's house, and walk along the passageway to Digory's. Unfortunately, along the way, they suddenly find that some of the floorboards are missing, and that taking a step forward would have them plummet to their deaths below." So they are walking step by step? But they can jump if needed. The process: they try to cross with current jump capability. If at some point they need to jump a gap larger than current capability, they fail at that gap, and they return (go back?) They then practice to be able to jump exactly that required distance (which is > current capability), taking one day. The next day they come back with new capability (that distance, and any lower). Then they resume from the start. They will attempt again, but might encounter another larger gap later.
We need to compute total days taken to complete crossing, given they start with L=1.
Days count: each time they need to improve their jump capacity, they spend a day training. The days count output is the number of training days? In examples: For "####" output 0, meaning they didn't need to train. For "##.#..#" output 2. Let's parse that.
Interpretation: We need to simulate the incremental improvement of jump capacity as they attempt to cross. They start from leftmost, and try to traverse using current L. They will always try to move as far as possible? Or they just try to go to the next board? Actually they are walking: they step from board to board, possibly jumping gaps. They can jump any distance ≤ L. They need to land on a board. They know the distance to the next board when they get to that point. But they don't know further gaps. So they will attempt to go forward until they get stuck: they encounter a gap that is larger than L. At that point, they realize they need to train to that gap length (the required jump length). They then go back (somehow) and train that length for a day, then return the next day with L set to that required length (or max of previously known and that? Actually they "master jumping a particular length L", and can jump any ≤ L. So after training they set L to the new length (since it's larger than old L). So L becomes exactly the required jump length they needed at that stuck point. Then they restart from the beginning, but now with larger L. They continue until they can cross.
But careful: In the description: "Note the following: At each point, they are able to sense only how much they need to jump at that point, and have no idea of the further reaches of the passage till they reach there. That is, they are able to only see how far ahead is the next floorboard." So when they are on a board, they look ahead and see the next board's distance (i.e., number of missing boards? Actually the distance: from current board to next board, measured perhaps as the number of steps? If they are on a board at position i (index), and the next board at position j>i, the jump required is j-i (the number of positions to skip? Usually if they stand on board and want to land on next board, they need to clear the gap of missing boards; the distance is the difference in indices. For example: string "##.#". positions:0 '#',1'#',2'.',3'#'. To go from position 1 '#' to position 3 '#', they need to jump over position 2, so the jump length is 2? But maybe they consider the "gap" as the number of consecutive '.'s? But typical such problems consider the jump length as the number of steps (i.e., distance between indices). However the examples need to be examined.
Example 2: "##.#..#". Let's list indices: 0 '#',1 '#',2 '.',3 '#',4 '.',5 '.',6 '#'. Wait length 7? Actually "##.#..#" has 7 characters: index0 '#',1 '#',2 '.',3 '#',4 '.',5 '.',6 '#'. Yes.
Now they start at index0 '#'. They can jump length ≤ L. Initially L=1. So they can only jump to adjacent positions (index+1). They "walk along the passageway": maybe they move step by step? If they can only jump 1, then they can only step to immediate next index if it is a board. But index1 is '#', so they can step onto it. Then from index1 to index2? But index2 is '.' missing, so they cannot step onto it. They need to jump over it. The next board is at index3. The distance from index1 to index3 is 2 (positions 2). To jump from index1 to index3, they need to cover a gap of length 2 (since they need to land on index3). But with L=1, they cannot. So they get stuck at index1, seeing the required jump length of 2 (the distance to next board). So they practice for L=2. That's one day.
Now after training, L=2. Next day, they start again. They can now jump distances ≤2. They go from index0 to index1 (step 1) then from index1 to index3? distance=2, they can do it. So they land on index3 '#'. Then from index3, the next board is at index6? Because positions: after index3, index4 '.', index5 '.', index6 '#'. The distance from index3 to index6 is 3 (positions 4,5,6? Actually difference = 3). But L=2, so they cannot jump 3. So they get stuck at index3, need to jump 3. They train for L=3. Another day. Total days = 2. That matches example output 2.
So indeed the jump length required is the difference in indices between consecutive '#' positions: if current board at i, next board at j, required jump = j - i.
But note: they could also possibly skip intermediate boards? Like if there is a board at index4, but they might be able to jump longer? But the process as described: they only see the distance to the next floorboard. That implies they always aim to go to the immediate next board (the next #) because they don't know about boards further ahead. However, once they have a larger L, they might be able to skip over some boards? Actually the problem statement: "they are able to sense only how much they need to jump at that point, and have no idea of the further reaches of the passage till they reach there. That is, they are able to only see how far ahead is the next floorboard." So when standing on a board, they can only see the distance to the next board (the first # after the current position). They cannot see beyond that. So they would always attempt to jump to that next board, not try to jump farther. This is consistent with the simulation above. So the traversal is deterministic: starting at leftmost #, they repeatedly jump to the immediate next # (the next board) using their current max jump L. If the required distance d > L, they get stuck, and must train to d. Then they restart from the beginning with new L = max(old L, d) (but d > old L so L becomes d). After training, they will be able to make that jump, and they continue.
Thus, the number of days equals the number of distinct times they encounter a required jump distance that exceeds their current max L, and each time they set L to that required distance.
But careful: could there be a scenario where they need to train for a certain distance, then later they encounter a smaller distance? That's fine; they have L covering it. Or they might encounter a larger distance later. So the process essentially picks a sequence of increasing distances: the required jumps between consecutive '#'s, as they traverse from left to right, but only those that are larger than all previous required jumps? Actually because when they get stuck at a jump, they train to that distance, then they can clear it. Then they continue. If later they encounter a jump that is larger than the new L, they'll need to train again. So the days count is the number of times the required jump distance is strictly greater than the maximum required jump encountered so far (starting with initial max = 1). But wait: initial max is 1, which is not a required jump; but if first required jump is >1, that counts. If a required jump is larger than any previous required jump, it will require a new training day. But is it possible that a required jump is not larger than the current max but still impossible? No, because current max is the largest they can jump, so any d ≤ current max is possible. So days = number of "record-breaking" required jumps, i.e., the number of times we encounter a gap d that is greater than the maximum d seen so far (starting with max=1). However, is it always that they will encounter gaps in order? The gaps are between consecutive #'s. They will traverse in order. So indeed, we need to count the number of gaps (consecutive distances) that are strictly greater than all previous gaps. And initial L=1. But note: The initial jump from start to the next board: There might be a board at index0 and then next board at index1 (distance=1). That's not >1, so no training. But if the next board is at index2 (like string "#.#"), distance=2 >1 => need training day 1, L=2. Then later from index2 to next board maybe distance=1? That's fine.
But wait: Could there be a situation where the required jump distance is larger than current L but not larger than a previously seen jump? But if it's larger than current L, it must be > current L. And current L is the maximum of all previously required jumps (since each time they set L to the required jump that was larger). So indeed, if we ever encounter a required jump that is larger than current L, it will be larger than any previous required jump because current L is exactly the max of all previous required jumps (since they set L to each required jump that caused training). So the count is simply the number of times the gap is larger than the maximum gap seen so far (including initial maximum=1). Alternatively, it's the number of "record high" gaps.
But let's test on the examples:
Example 2: gaps between consecutive #: positions: 0,1,3,6. Gaps: (1-0)=1, (3-1)=2, (6-3)=3. Starting max=1. Compare: gap1=1 not >1, skip. gap2=2 >1 => record, count=1, new max=2. gap3=3 >2 => record, count=2. output=2. matches.
Example 3: "##..#.#". Let's index: 0 '#',1 '#',2 '.',3 '.',4 '#',5 '.',6 '#'. Consecutive # positions: 0,1,4,6. Gaps: (1-0)=1, (4-1)=3, (6-4)=2. Starting max=1: gap1=1 not >1; gap2=3 >1 => record, count=1, max=3; gap3=2 not >3. So count=1. Output=1. matches.
Example 4: "##.#....#" Let's parse: string "##.#....#" has length? Count: characters: # # . # . . . . #? Actually "##.#....#" -> positions: 0 '#',1 '#',2 '.',3 '#',4 '.',5 '.',6 '.',7 '#', maybe? Wait let's count: after "##.#....#" there are: indices: 0:'#',1:'#',2:'.',3:'#',4:'.',5:'.',6:'.',7:'#'? That's 8 characters? Actually "##.#....#" has 2 #, then ., then #, then 4 '.'? "...." four dots, then #. So total length = 2+1+1+4+1 = 9? Let's write: "##" (2), "." (1) -> "##.", then "#" -> "##.#", then "...." -> "##.#....", then "#" -> "##.#....#". So length = 2+1+1+4+1 = 9. Indices 0-8. So positions: 0 '#',1 '#',2 '.',3 '#',4 '.',5 '.',6 '.',7 '.',8 '#'. Consecutive # positions: 0,1,3,8. Gaps: 1-0=1, 3-1=2, 8-3=5. Starting max=1: gap1=1 not >1; gap2=2 >1 => record, count=1, max=2; gap3=5 >2 => record, count=2. Output=2. matches.
So indeed the answer for each string is the number of gaps (differences between consecutive indices of '#') that are > the current maximum gap encountered so far (starting with max=1), i.e., count of "record" gaps.
But wait, need to consider if they might have to train even if the gap is exactly 1? No, they can already jump 1. So no training.
Thus the answer is simply: Given the positions of '#' in order, let gaps = positions[i+1] - positions[i] for i=0..k-1 (where k+1 positions). Count how many gaps are > previous maximum gap, with initial maximum = 1.
But careful: The initial ability is to jump length 1. But what if the first gap is 0? Not possible because consecutive positions are distinct. So fine.
Edge cases: The string starts and ends with '#', so there is at least two positions? Possibly string length 1: "#"? But constraints say |P| ≥ 1 and first and last characters are '#', so length 1 is allowed? Then there is only one #, meaning start and end at same position? That would mean they are already at Digory's? But passage might be length 1? Then no jumps needed. Days=0. But we should handle that: if there's only one #, no gaps, answer 0.
But note: It's possible that there are consecutive '#' with gap 1, or gaps bigger.
So algorithm: For each test case, iterate over the string, keep track of previous '#' position prev. Also maintain current maximum gap seen so far (max_gap = 1 initially) and count = 0. For each character, if it's '#', compute gap = current_index - prev if prev != -1 (i.e., not first '#'). If gap > max_gap, increment count and set max_gap = gap. Then set prev = current_index. That's O(n) per test case, with total O(total length). That is fine given constraints: total length ≤ 5e6, T ≤ 1e6 but total length limited.
But there's nuance: Could they possibly decide to jump differently? The description says: "they are able to sense only how much they need to jump at that point, and have no idea of the further reaches of the passage till they reach there. That is, they are able to only see how far ahead is the next floorboard." That implies they always aim for the next board, not skip any. So the above is correct.
Now, is there any scenario where they might need to train for a gap that is not strictly greater than previous max because they might not have the ability to reach that board? But they always start at index0 and go step by step. As long as they can clear each gap, they proceed. So it's fine.
Thus the solution seems straightforward.
But wait, there is a catch: The process says: "At each point, they are able to sense only how much they need to jump at that point, and have no idea of the further reaches of the passage till they reach there. That is, they are able to only see how far ahead is the next floorboard." This indicates that they don't know the distance to the next board until they are at the current board? Actually they sense it when they reach that point. So the simulation is exactly as we did.
Now, we must verify the example: "####". Gaps: positions 0,1,2,3: gaps 1,1,1. max start 1, none >1, count 0. OK.
Everything matches.
Thus answer = number of gaps strictly larger than any previous gap, starting with threshold 1.
But let's double-check with some edge cases:
-
"#.#" -> gaps: from 0 to 2? Actually positions: 0,2. Gap = 2. Compare to max=1: 2>1 => count=1. So answer =1. Let's think: They start L=1, from index0, see next board at index2 distance=2 >1, cannot jump, train for 2 days? Actually only 1 training day needed? They train for 2, then next day they can jump 2 and reach the end? So days=1. Good.
-
"#..#" -> positions: 0,3. Gap=3 >1 => count=1. answer=1.
-
"#...###" -> positions: 0,4,5,6. gaps: 4,1,1. Only first gap 4 >1 => count=1. But is that correct? Let's simulate: start L=1, at index0 see next board at index4 distance=4 >1 => train L=4. Next day, can jump 4 to index4. Then from index4 to index5 gap=1 <=4 ok, index5 to index6 gap=1, done. So only 1 training day. Yes.
-
"##...##" -> positions:0,1,5,6? Actually string "##...##" indices:0#,1#,2.,3.,4.,5#,6#? Wait length 7? Actually "##...##" has 2 #, then 3 dots, then 2 #: indices:0#,1#,2.,3.,4.,5#,6#. Consecutive # positions: 0,1,5,6. gaps:1,4,1. Records: 1 not >1; 4>1 => count=1; 1 not >4. So answer=1. Simulate: L=1: start at 0, go to 1 (gap1). At 1, next board at 5 distance=4>1 => stuck, train 4. Next day L=4: from 0->1 (or maybe they could skip 1? They only aim for next board, which from 0 is 1 distance1 <=4; they step to 1? But they might consider going from 0 directly to 5? They only see next board, which is at 1 because it's the immediate next #. They don't see 5. So they would go to 1 first. Then from 1 they see next board at 5, distance4, they can jump. So after training, they can make that jump and then from 5 to 6 gap1, done. So indeed 1 day.
-
"#.##" -> positions:0,2,3? Actually string "#.##": indices 0 '#',1 '.',2 '#',3 '#'. Consecutive #: 0,2,3. gaps:2,1. Records: 2>1 => count=1; 1 not >2 => total 1. Simulate: L=1: from 0, next board at 2 distance2>1 => train 2. Next day L=2: from 0 to 2 (gap2), then 2->3 gap1, done. So 1 day. Ok.
-
"###...###...###" etc.
Thus solution is simple.
But wait, there might be nuance: the initial ability is to jump a length of 1. They can also "walk" on boards? It says they can jump any amount less or equal. So stepping onto an adjacent board is a jump of length 1. That's fine.
Now we must ensure that the problem statement might be interpreted differently: Could it be that they don't necessarily need to jump to the immediate next board? Because they can see only the next floorboard, but if they can jump further, they might consider skipping it? However, the text: "they are able to only see how far ahead is the next floorboard." So they don't know what's beyond that. If they can jump further than that distance, would they still jump exactly that distance to land on that board, or would they try to jump farther but don't know if there is a board? Since they don't know, they wouldn't risk jumping into empty space. So they would jump exactly to the next board they see. So they always jump to the immediate next #. So our approach stands.
But consider a scenario: After training, they can jump up to L which is larger than some gaps. They still jump to the immediate next board. So it's consistent.
Now we need to handle extremely large input: T up to 1e6, total length 5e6. So reading input efficiently is crucial. We must not store all strings for all test cases simultaneously if we process one by one? We can read line by line, process each string, output answer per line. Use fast I/O (like sys.stdin.buffer.read() and parse). In Python, we can read all input at once and split. Because total length is 5e6, that's fine. But T can be 1e6, meaning we have up to 1e6 lines. Splitting into lines is okay if we read as bytes and splitlines. But careful: each line includes the string. The total input size is about sum(|P|)+T newlines, roughly up to 5e6 + 1e6 = 6e6 bytes, which is fine. So we can read all, split into lines, then skip first line (T) and iterate through the lines (each string). For each string, compute answer using a simple loop.
But we must be careful about the memory overhead of storing all lines as separate strings; we can process one at a time using sys.stdin.readline in a loop. But T up to 1e6, using Python's sys.stdin.readline may be okay if we use .buffer and .readline? But each call has overhead; perhaps reading all and splitting is okay given 6e6 bytes. But splitting into a list of 1e6 strings each of average length 5? Actually total length 5e6 across all test cases, so average length 5. So number of strings large but each small, overhead of many small objects might be high but still manageable? 1e6 strings might be heavy (memory ~ overhead). Better to read line by line using sys.stdin.buffer.readline, and process each string immediately. Because Python can handle 1e6 iterations of a simple loop fine? 1e6 is borderline but possible if the per-test processing is O(length) and total length is 5e6, so total operations ~5e6 plus loop overhead ~1e6, which is fine (like 0.1-0.2 seconds per million? Actually Python loop overhead for 1e6 iterations is not huge (maybe 0.05 secs). But we also need to process each character. Overall we might be okay within time if optimized. But we need to consider that T can be as high as 1e6, and we have to read that many lines. Using input() is slower; using sys.stdin.buffer.readline is fast. We'll use that.
But there's a catch: The input might have blank lines? Probably not.
Also, we need to output T lines with answers.
Simplify processing: For each string s (bytes or str), we iterate over its characters. Since s is a string of '#' and '.', we can do:
prev = -1
max_gap = 1
count = 0
for i,ch in enumerate(s):
if ch == '#':
if prev != -1:
gap = i - prev
if gap > max_gap:
count += 1
max_gap = gap
prev = i
But careful: We are using 0-indexed indices. That's correct.
But we need to ensure that we don't count the last gap if it's not needed? Actually we compute gaps between consecutive #s. That's all.
Edge: If the string length is 1 and it's '#', then prev will be set to 0 and no gaps computed, count=0.
Works.
Now, but think about the initial max_gap = 1. However, what if the first gap is 1? That's not >1, so not counted. But is it possible that they need to train for a jump of length 1? No, because they start with ability 1. So fine.
But consider a string like "#.#.#". positions: 0,2,4. gaps: 2,2. First gap 2 >1 => count=1, max_gap=2; second gap 2 not >2 => count=1. So answer=1. Simulate: L=1: stuck at first gap 2 => train 2; next day L=2: from 0 to 2, then from 2 to 4 gap=2 ≤2, can jump. So 1 day. Good.
Now, consider string "#..##...##" but not needed.
Alright.
But is there any scenario where they might need to train for a gap that is not between consecutive # but some other? Suppose they could skip some boards and encounter a larger gap? But they don't know about later boards, so they always go to the immediate next. So it's fixed.
Thus problem reduces to counting record gaps.
Now, we must ensure correctness for all constraints. But wait, maybe there is nuance: The process says "they start by being able to 'jump' a length of 1." But does this mean they can only jump exactly 1? But they also say "once they have mastered jumping a particular length L, they are able to jump any amount less than equal to L as well." So they can jump up to L. So fine.
Another nuance: Could they possibly decide to walk on existing boards without jumping? The act of stepping onto an adjacent board is a jump of length 1. So it's fine.
Now, one more check: The example 1 output 0, meaning they didn't need any training. For "####", that's clear.
Now, we should test some more:
-
"#." Not allowed because last character must be '#'. So fine.
-
"##" -> gaps:1, none >1 -> 0. Simulate: L=1, from 0 to 1 gap1, done. 0 days.
-
"#..#." invalid last char not #.
Alright.
Thus the solution is simple.
But wait, the problem might be more subtle: It says "The amount they choose to practice for their jump is exactly the amount they need to get across that particular part of the passage." That is, if they need to jump length L1 > L0, they practice jumping length L1 that day. So they set L = L1, not the maximum of previous and L1? But L1 > L0, so new L is L1, which is > all previous. So L always equals the max gap encountered so far.
Thus answer = number of times we find a gap larger than current maximum.
Therefore we can implement.
But let's consider if there is a possibility of "training" for a gap that is not strictly increasing? Suppose they encounter a gap that is larger than current L but maybe there was an earlier larger gap that they didn't encounter because they got stuck earlier? But they always start from the beginning each day, so they will eventually encounter all gaps in order. The only way they would not have encountered a larger gap earlier is if there was a larger gap earlier but they didn't need to train for it because they could jump it? But if it's larger than current L, they would have been stuck at that earlier gap. So they would have trained then. So the sequence of gaps they train on is strictly increasing and corresponds to record gaps.
Hence correct.
Now complexity: O(total length) time, O(1) extra per test.
Implementation details:
We'll read T, then loop T times, reading each line, strip newline. Since strings can be large (up to 1e6 each), but total 5e6, using .strip() or .rstrip('\n') is fine. Use .decode if reading bytes.
We'll output answers as strings with newline.
Potential pitfalls: The input may contain spaces? No, only the string.
Edge Cases: The string might be empty? But constraints say |P|≥1.
If there are multiple test cases and we use sys.stdin.buffer.readline, we need to be careful about trailing newlines. We'll use .rstrip(b'\n') or .decode().strip().
But using .strip() will also remove leading/trailing spaces? Not needed.
Better to read all as bytes and split by whitespace, but that would treat each token as a string; however the input is line-based: first line T, then each line contains the string. Splitting by whitespace would also split if there are spaces? There aren't. So we can read all bytes, split by whitespace, first token is T, then each subsequent token is a test string. That would be efficient and avoid line-by-line overhead. With total size ~6e6, splitting into list of tokens (1e6+1 tokens) is memory heavy but maybe okay? 1e6 tokens, each a small bytes object overhead maybe ~37 bytes each, total ~37 MB plus string data ~5 MB, so about 42 MB, which is acceptable? Might be borderline but likely okay for typical memory limits (256 MB). However, Python overhead per bytes object is significant (like 33 bytes + length). For 1e6 objects, that's ~33 MB overhead plus the actual data (5 MB). Plus list overhead (8 MB). So total maybe 50-60 MB, which could be okay but might risk memory limit. Safer to process line by line without storing all tokens.
But line-by-line reading of 1e6 lines with .readline in a loop is also fine; each line we process and discard. Use sys.stdin.buffer.readline to read lines.
But Python's .readline for 1e6 calls might be slower than reading all at once? But we can use sys.stdin.buffer.read().splitlines()? That would create a list of lines (1e6+1). Similar memory issue.
Given total input is only about 6 MB, reading all into a bytes object and then splitting lines might be acceptable memory-wise: A list of 1e6 lines would be large, but maybe still within memory (each line is a bytes object). However, typical memory limit might be 256 MB or 512 MB. Let's estimate more precisely:
Suppose average line length (excluding newline) is about 5 characters (since total length 5e6 across 1e6 lines, average length 5). For each line, Python bytes object overhead: on 64-bit CPython, bytes object has overhead: PyObject header (16 bytes) + ob_shash (8) + ob_size (8?) Actually for bytes, the memory layout: PyObject_VAR_HEAD (reference count, type pointer, size) plus the data. Overhead is about 33 bytes (PyObject_HEAD 16, plus ob_size 8? Actually I recall: bytes object overhead ~33 bytes + data size (aligned?). Let's approximate 33 bytes overhead + data length (1 per byte). So for average length 5, each bytes object uses ~38 bytes. For 1e6 objects, that's 38 MB. The list of 1e6 pointers: each pointer 8 bytes, so 8 MB. Plus the initial bytes of input (6 MB) maybe already included? Actually the data is stored in each bytes object separately; they duplicate the string data, which is 5 MB. So total ~38+8 = 46 MB plus maybe some overhead for list. That's under 100 MB. So it's likely okay. However, memory fragmentation and Python's additional overhead might push it higher but still likely within 256 MB. So both approaches are acceptable.
But we can be even more memory efficient: Process line by line using a generator reading from sys.stdin.buffer, but still need to call readline 1e6 times. That might be slower due to Python function call overhead but total 1e6 calls is fine. Typically, reading line by line with .readline in a for loop is acceptable for 1e6 lines. I'd prefer that for simplicity and lower memory.
But note: There is a potential pitfall: The input may have large strings up to 1e6 characters. For those, reading line by line is fine.
I'll implement:
import sys
def solve():
data = sys.stdin.buffer.read().split()
# first token is T, rest are strings
# But careful: The strings may contain only # and . and no spaces, so split works.
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
s = next(it).decode() # or keep as bytes and compare to ord('#')?
# we can treat bytes directly: if ch == 35 (ord('#')). That might be faster.
# Let's use bytes to avoid decode. We'll keep as bytes.
Actually we could keep as bytes and compare to b'#'? But iterating over bytes yields ints (0-255). So we can do for c in s: if c == 35 (since '#' is 35). That's efficient.
So:
s = next(it) # bytes
prev = -1
max_gap = 1
count = 0
for i, c in enumerate(s):
if c == 35: # '#'
if prev != -1:
gap = i - prev
if gap > max_gap:
count += 1
max_gap = gap
prev = i
out.append(str(count))
sys.stdout.write("\n".join(out))
But note: Using .split() splits on any whitespace. Since each test string is on its own line, and contains only # and ., no spaces, .split() will give us exactly the tokens: first T, then each string. This will also remove newline characters. That is fine. However, what if a test string is very long and contains no spaces? It's fine. Also .split() returns list of bytes if input is bytes? Actually sys.stdin.buffer.read() returns bytes, and .split() with no arguments splits on any whitespace and returns list of bytes. So we have a list of bytes tokens. So first token is T as bytes; convert to int via int(token). Then each subsequent token is the string as bytes. So we can process them as bytes.
But careful: The string could contain newline as part of it? No, each string is on its own line, so .split() will separate correctly.
Now, is there any risk that the string contains spaces? No.
Thus this approach reads all input, splits into tokens, and processes each token as the test string. But note: The input format is: first line T, then T lines each containing P. Using .split() will treat each line as a token because there is no whitespace within the line. So tokens are exactly T+1 tokens. That works.
But what about case when T=1,000,000 and total length 5,000,000. Then number of tokens = 1,000,001. That's okay. Memory usage: 1,000,001 bytes objects, each representing a line (string). Overhead as estimated. Should be okay for 256 MB? Let's compute more accurately:
In CPython 3.9, bytes object overhead: I recall that for small bytes objects, the memory is: PyObject (16) + ob_size (8) + maybe some extra? Actually in CPython, the structure for bytes is:
typedef struct {
PyObject_VAR_HEAD
Py_hash_t ob_shash;
char ob_sval[1];
} PyBytesObject;
PyObject_VAR_HEAD includes PyObject_HEAD (ob_refcnt, ob_type) and ob_size. For 64-bit, PyObject_HEAD is 16 bytes (8 refcnt, 8 type). ob_size is 8 bytes. ob_shash is 8 bytes. So total overhead = 16+8+8 = 32 bytes, plus the data array which is ob_size+1 bytes (including null terminator). But the memory allocator might round up. So overhead ~33 bytes plus data. So for a bytes object of length L, total memory ~ 33 + L + 1 (null) = L+34 approx, rounded to multiples of 8 perhaps. For L=5 average, ~39 bytes. For 1e6 objects, ~39 MB. Plus list overhead: list of 1e6 pointers: each pointer 8 bytes, so 8 MB. Plus the token for T (small). So total ~47 MB. Plus the input bytes read originally: that's a single bytes object of size ~6 MB, but after splitting we have separate bytes objects; the original bytes object still exists (the data from read()) until we free it; but we can discard it after splitting? Actually we do data = sys.stdin.buffer.read().split(), which reads all into a bytes object, then split creates new bytes objects by slicing the original? In Python, .split() on bytes returns a list of new bytes objects that are created by copying? I think for bytes, split returns new bytes objects each containing a copy of the slice. Because bytes are immutable, but .split() likely creates new bytes objects by slicing, which copies the data? Actually slicing bytes returns a new bytes object that is a copy? Wait, in Python, slicing bytes returns a new bytes object that is a copy of the data (since bytes are immutable, a slice must copy because it's a new object). But I think .split() on bytes uses PyBytes_FromStringAndSize to create new bytes objects from the data without copying? Let's check: In CPython, bytes.split() likely returns new bytes objects that are views? Actually, for memory efficiency, .split() on bytes may allocate new bytes objects that copy the data, because the original bytes object is contiguous and the slices are contiguous; but bytes objects always contain a copy of the data when created via slicing? Actually slicing bytes: b'abc'[1:2] returns b'b', which is a new bytes object containing a copy of that single byte? I recall that slicing bytes creates a new bytes object that copies the data. There is no view for bytes (unlike memoryview). So each token would be a copy of the substring, meaning the data is duplicated. So total memory would be original bytes (size ~6 MB) plus copies for each token (total data size also ~5 MB) plus overhead. That doubles memory but still ~12 MB data. Still okay.
But if we want to be more memory efficient, we could read line by line using .readline and not duplicate. However, simplicity often wins. But there is T up to 1e6, and we will create a list of 1e6 strings anyway for output? Actually we need to output answers line by line. We could accumulate in a list of strings and then join. That list will have T strings (answers), each small (like up to maybe 6 digits if answer large). That's okay, 1e6 small strings overhead ~ maybe 40 MB? For answers, each as string, average length maybe 2-3 digits? Actually maximum answer? The maximum gap can be up to length of string (1e6), so answer number of record gaps could be up to something like number of distinct gaps? In worst case, if gaps are strictly increasing, e.g., positions: 0,1,3,6,10,15,... The number of gaps could be up to about sqrt(2*n) maybe? Actually if gaps increase by at least 1, the sum of gaps = n-1 (approx). So max number of gaps is O(sqrt(n)). For n=1e6, maximum number of gaps if gaps are 1,2,3,... then sum = k(k+1)/2 ≤ n => k ~ sqrt(2n) ~ 1414. So answer max about 1414. So each answer as string up to 4 digits. So 1e6 answers strings: overhead per string ~49 bytes (similar to bytes) plus data, total maybe 50 MB. So output list may also be large. But we can write output line by line using sys.stdout.write inside loop, but that may be slower due to many writes? Better to accumulate in list and join at end? But 1e6 lines: if we join, we create a huge string of maybe ~5 MB (since each answer avg 3 digits + newline = 4 bytes => 4 MB). That's fine. The list of 1e6 answer strings may have overhead 1e6 * pointer + string object overhead. That's another ~50 MB. So total memory might be 50 MB (answers) + 50 MB (input tokens) + 12 MB data = 112 MB, still acceptable. But we can reduce memory by not storing all answer strings; we could build output incrementally using a write buffer, e.g., using sys.stdout.write for each answer with newline. However, 1e6 separate writes may be slower due to system calls. Python's sys.stdout is buffered by default (line buffered?), but calling write many times may still be okay. But for 1e6 writes, it might be okay; but we can also accumulate in a list and then join for speed. Usually for high T, building a list of strings and then doing one write is faster. But memory overhead is okay. However, we must ensure overall memory stays under limit. Many judges have memory limit 256 MB or 512 MB. 112 MB is fine.
But we could also process each test case, compute answer, append to an array of strings (or use a bytearray to accumulate output) to reduce overhead. For 1e6 answers, using an array of strings is okay.
Nevertheless, the simplest: read all lines via sys.stdin.buffer.read().splitlines()? Actually using split() is simpler. But note: split() splits on any whitespace, which includes spaces. Since input lines have only the string, that's fine. But if there are empty lines? Should not.
Alternatively, we can use sys.stdin.buffer.readline() to read first line for T, then loop T times reading each line, strip newline, process. That way we only have one string at a time, and we can output as we go, collecting output maybe in a list or writing. That's even more memory efficient: we only store one test string at a time, and output answer immediately. We can accumulate answers in a bytearray for faster output. Let's do that to be safe with memory.
Implementation:
import sys
def solve():
import sys
data_in = sys.stdin.buffer
t_line = data_in.readline()
while t_line.strip() == b'': # skip empty? but unlikely
t_line = data_in.readline()
T = int(t_line)
out_lines = []
# We'll accumulate answers as strings in list, then join at end; but we can also use a bytearray.
# Use bytearray for speed.
out = bytearray()
for _ in range(T):
line = data_in.readline()
# Possibly the line may be empty if input is malformed? But assume not.
# Strip newline: rstrip(b'\n') but keep other whitespace? Not needed.
s = line.rstrip(b'\n')
# It's possible that the line might have trailing carriage return? Use .strip()? Better to only remove newline.
# But if the string is huge, .rstrip(b'\n') is fine.
prev = -1
max_gap = 1
count = 0
# iterate over bytes
for i, c in enumerate(s):
if c == 35: # '#'
if prev != -1:
gap = i - prev
if gap > max_gap:
count += 1
max_gap = gap
prev = i
# Append answer as string plus newline
out.extend(str(count).encode())
out.append(10) # newline
sys.stdout.buffer.write(out)
if name == "main":
solve()
But careful: The input may have lines that are empty? If the string is empty? Not allowed.
Now, test with given examples.
Let's test manually.
Example input:
4
##.#..#
##..#.#
##.#....#
Our code: T=4, then read lines. First test string: "####". Process: positions 0,1,2,3; gaps: 1,1,1 -> max_gap stays 1 -> count 0. Output "0\n". Second: "##.#..#": we saw count 2. Third: "##..#.#": count 1. Fourth: "##.#....#": count 2. Output matches.
Now edge: What about string with multiple consecutive '#'? fine.
Now, consider a case where there is a gap exactly equal to current max_gap. That does not trigger training. But is it correct? For example, after training to jump L, if they encounter a gap exactly L, they can jump it because they can jump any amount ≤ L. So no training. So strict > is correct.
Now, think about the initial max_gap = 1. If the first gap is 1, no training. But what if the first gap is 0? Not possible because positions are increasing.
Thus algorithm correct.
But wait: Could there be a scenario where they get stuck not because of a gap to the next board, but because they cannot even step onto the first board? The first character is '#' so they are already on a board. So okay.
Thus final answer is as above.
Now, let's consider if the problem might have a twist: The passage string includes '.' and '#', but the characters represent floorboards; maybe a '#' indicates presence, and they can stand on it. They start at position 0, which is '#', and need to reach the last character (n-1), which is '#'. They can only move by jumping from one '#' to another '#', and they can only see the next '#' when standing on a '#'. That's our interpretation.
Now, confirm with more examples: Suppose P = "#.#.#.#". This yields gaps: 2,2,2,... all 2. First gap >1 => count 1, then max=2, others not >2 => count=1. So answer=1. Simulate: L=1, stuck at first gap 2 -> train 2. Next day L=2: can jump all gaps. So 1 day.
Suppose P = "#..##" => indices:0,3,4? Actually "#..##": positions 0 '#',1 '.',2 '.',3 '#',4 '#'. Consecutive #: 0,3,4 gaps:3,1. First gap 3>1 => count=1, second gap 1 not >3 => 1 day. Simulate: L=1: stuck at gap 3, train 3. Next day L=3: from 0 to 3 (gap3), then 3->4 gap1, done. 1 day. Good.
Suppose P = "#.#...#" => positions:0,2,6 gaps:2,4. Count: 2>1 =>1, 4>2=>2. So answer=2. Simulate: L=1: stuck at gap2, train2. Next day L=2: from 0 to 2 gap2, then next gap from 2 to 6 is 4 >2 => stuck at 2, train 4. Next day L=4: can cross. So 2 days. Good.
Thus algorithm works.
Now, consider if there are leading '.'? First char must be '#' per constraint. So fine.
Now, about constraints: total length across testcases ≤ 5e6. So O(total length) solution is fine.
Thus final code as above.
But we must be careful about reading input: using data_in.readline() for each test case might be slower but still okay for 1e6 lines? Let's estimate: reading 1e6 lines with .readline() may be okay if the lines are short. In Python, .readline() on a buffered reader is relatively fast. But each call involves Python overhead. For 1e6 lines, it's maybe 0.2-0.4 seconds? Not sure. But total runtime could be within typical 2-3 seconds if optimized? We need to ensure not too slow. Let's benchmark conceptually: 1e6 iterations of a simple loop with a .readline() and some processing (enumerating characters) might be near time limit? But the total characters processed is 5e6, so average per test is 5 chars. So the overhead of loop and function calls might dominate. But 1e6 iterations is okay; many Python loops of 1e6 are ~0.1s for simple arithmetic. However, with .readline() each call may involve some overhead, but still likely within 1 sec. But we need to consider that reading 1e6 lines from stdin might be slower due to system calls? Actually sys.stdin.buffer uses buffered I/O; .readline() reads from buffer, not system call each time. So it's relatively fast.
But we could also use sys.stdin.buffer.read().splitlines() to get all lines at once, then iterate over the list. That might be faster because it reads all in one go and splits. Then we avoid 1e6 calls to .readline(). However, we then store all lines in memory. That is okay. Let's decide: I'll go with reading all and splitting into lines using .read().splitlines()? But careful: .splitlines() returns list of lines without newline. That's similar to .read().split(b'\n') but .splitlines() also handles other line endings. For bytes, .splitlines() returns list of lines without line breaks. That's fine. Then we have a list of lines (including first line T). We can process accordingly.
But using .read().split() is simpler because it splits on whitespace, which gives us tokens. But then the string tokens are the lines without whitespace. However, if a line is empty? Not possible. So .split() works.
I'll use .read().split() to get tokens. Then first token is T, then rest are strings. However, .split() will split on any whitespace, but if a string contains spaces (it doesn't), that would break. But it's safe.
Now, what about the possibility that some lines have trailing spaces? Unlikely. So .split() is okay.
But .split() returns a list of bytes. Then we can process them.
But if we use .split(), we need to ensure that the newline characters are removed. They will be.
Now, I'll implement using .split() to avoid loop of readline calls.
Pseudo:
def solve():
import sys
data = sys.stdin.buffer.read().split()
if not data: return
t = int(data[0])
out = bytearray()
idx = 1
for _ in range(t):
s = data[idx]; idx+=1
prev = -1
max_gap = 1
count = 0
for i, c in enumerate(s):
if c == 35: # '#'
if prev != -1:
gap = i - prev
if gap > max_gap:
count += 1
max_gap = gap
prev = i
out.extend(str(count).encode())
out.append(10)
sys.stdout.buffer.write(out)
Check: data length should be t+1. If there are extra whitespace? Should be exactly t+1.
But what if some test string contains whitespace? Not.
This approach reduces overhead of reading lines one by one, but uses memory for list of tokens. As argued, memory is okay.
I'll go with this.
Now, we must consider performance of enumerating bytes: for each character we do a check. Since total characters is 5e6, that's fine.
Potential micro-optimizations: Instead of enumerate, we can iterate over indices and fetch bytes using s[i], but enumerate is fine.
We could also convert to a memoryview? Not needed.
Edge Cases: If there is only one '#' in the string, then we never enter the if prev!=-1 block, count remains 0, output 0.
Now, confirm with example: all good.
One nuance: The initial max_gap = 1. But what if the first gap is also 1? That's fine. But consider if the first gap is exactly 1, but later they need a gap of 1 again? That's fine.
But is there any situation where they might need to train for a gap that is exactly equal to current max but they cannot because they can only jump up to L inclusive? If they can jump up to L inclusive, then equal is okay. So no training.
Thus answer is count of times a gap exceeds the maximum gap seen so far.
Thus we have solved.
Now, I'll produce final answer with explanation.
But before finalizing, I'll test some random cases with a quick mental simulation.
Case: "###..##...####" compute positions: 0,1,2,5,6,10,11,12,13? Actually "###..##...####": indices:0#,1#,2#,3.,4.,5#,6#,7.,8.,9.,10#,11#,12#,13#? Wait length? Let's compute: "###" -> 0,1,2; then ".." -> 3,4; then "##" ->5,6; then "..." ->7,8,9; then "####" ->10,11,12,13. So positions: 0,1,2,5,6,10,11,12,13. Gaps:1,1,3,1,4,1,1,1. Records: max=1 initially; gap1=1 not >; gap2=1 not; gap3=3>1 => count=1, max=3; gap4=1 not; gap5=4>3 => count=2, max=4; rest not. So answer=2. Simulate: L=1: walk to index2 (gaps 1,1). At index2, next board at 5 gap=3 >1 -> stuck, train 3. Next day L=3: from start, can jump gaps: 0->1 (1), 1->2 (1), but they would step on each board because they only see next. From index2, gap3=3 <=3 so jump to 5. Then from 5 to 6 gap1. From 6, next board at 10 gap=4 >3 -> stuck, train 4. Next day L=4: can cross. So 2 days.
Works.
Now, think about scenario where there is a gap that is exactly the same as a previous larger gap but they haven't encountered that previous larger gap? Not possible because they encounter gaps in order.
Thus solution stands.
Now, I'll produce final output.
But before final, check if there is any alternative interpretation: Could the jump length be measured as number of missing floorboards? For example, between # and # with one '.' in between, that's a gap of 1 missing board, so they need to jump over 1 missing board, distance maybe 2? But examples show that from position 1 to 3 (with one '.' at 2) required jump was 2, which is index difference. So they treat jump length as the distance between positions. Good.
Now, I'll finalize.
Potential pitfalls: In Python, using enumerate on a bytes object gives integers (the byte values). So c == 35 works.
Now, test with large string: If string length 1e6, the loop will be fine.
Now, about T up to 1e6: The outer loop for _ in range(t) will be 1e6 iterations. That's okay. The inner loop total across all tests is 5e6 iterations, so average per test is small. So overall time is dominated by loop overhead for T, but 1e6 loops is manageable (maybe ~0.2s for just loop, plus processing). Likely under 2 seconds.
But we need to be careful with Python's speed for 1e6 loops plus 5e6 char checks. Should be okay. However, to be safe, we could use a faster method: For each string, we can find indices of '#' using something like numpy? Not needed.
We could also compute answer by scanning string and using while loops to find consecutive # positions, but our method is fine.
One micro-optimization: Since we only care about gaps, we could use a while loop to find positions of '#', but enumerate is fine.
Alternatively, we can manually iterate over bytes and maintain a counter for distance since last '#', but we need gaps only when we encounter '#'. Actually we can keep last_position and when we see '#', compute gap as index - last_position if last_position != -1, then update. That's what we do.
Now, to avoid Python's enumerate overhead, we can use a simple for loop with index variable i manually incrementing. But enumerate is implemented in C and is fast. So okay.
Thus final solution as described.
Now, we should also consider the possibility that the string contains newline at the end? Our .split() removes it, so fine.
Now, final code:
import sys
def main():
data = sys.stdin.buffer.read().split()
if not data:
return
t = int(data[0])
out = bytearray()
idx = 1
for _ in range(t):
s = data[idx]
idx += 1
prev = -1
max_gap = 1
days = 0
# iterate over bytes
i = 0
# using while loop may be faster? but for loop is fine.
for i, c in enumerate(s):
if c == 35: # '#'
if prev != -1:
gap = i - prev
if gap > max_gap:
days += 1
max_gap = gap
prev = i
out.extend(str(days).encode())
out.append(10)
sys.stdout.buffer.write(out)
if name == "main":
main()
But we need to be careful: The variable 'i' from enumerate is used; it's fine.
Testing with example:
Input:
4
##.#..#
##..#.#
##.#....#
We'll get "0\n2\n1\n2\n". Good.
Now, test a case with single '#': input: 1\n#\n. Our code: s = b'#', enumerate yields (0,35). prev = -1, then see '#': if prev == -1, set prev=0, no gap. No days. Output 0. Good.
Now, test with something like "#.#": input: 1\n#.#\n. s = b'#.#', positions: 0 and 2. prev -1 => set prev=0 at first #; then at index1 '.' skip; index2 '#': gap=2-0=2 > max_gap=1 => days=1, max_gap=2. Output 1. Good.
Thus final answer.
Now, we should also consider potential overflow? Not an issue.
Now, there is a subtle point: The problem says: "they start by being able to 'jump' a length of 1." So initial max = 1. But could there be a scenario where the first gap is 0? No.
All good.
Now, just to be thorough, let's consider if they could potentially skip some boards by jumping longer than the immediate next, but they don't know it's there. So they wouldn't. So fine.
Now, some might interpret the process as: They start at Polly's house, walk until they see a missing board, then they need to jump the gap. The distance they need to jump is the number of consecutive '.'s? Actually if they stand at a board and the next board is after k '.'s, the gap length could be defined as k+1? But the examples show that from index1 to index3 (with one '.' at index2) they needed jump length 2. That's consistent with index difference. If we considered the number of missing boards, that would be 1, not 2. So it's definitely index difference.
Thus solution is correct.
Now, we need to produce final answer in the required format.
I'll include explanation in the solution.
But the instruction: "Digory Kirke and Polly Plummer ... Find how many days it will take them to cross the passageway." So output days.
Now, I think that's it.
Now, final answer: code as above.
But maybe we can further optimize: Because T can be 1e6, and we are using out.extend(str(days).encode()) which creates a new bytes object each time? Actually str(days).encode() creates a bytes object; we can instead use out += str(days).encode() which is similar. But extend expects an iterable of ints; bytes is iterable of ints (0-255). So it's fine. However, each call to str() and encode() creates new objects. That's okay; 1e6 calls may be okay, but we could possibly avoid by using a preallocated list and join, but we already have a list of answer strings. Using out.extend is efficient.
Alternatively, we could accumulate answers in a list of strings and then "\n".join them. That might be slightly more efficient because it creates one large string. But it also creates many intermediate string objects. Both are fine.
I'll stick with out bytearray.
Now, check memory: out bytearray will contain about 4-5 MB of data, which is fine.
Thus final.
One more nuance: In the input, there could be spaces after the string? The problem says each line consists of the string P. So no trailing spaces. But if there were, using .split() would remove them, which might change the string if it contains spaces? But it doesn't. So safe.
However, .split() splits on any whitespace, so if the string itself contains spaces (not possible), it would break. So it's fine.
Edge case: Some lines may be longer than available? Not.
Now, final code ready.
But I recall that Python's .split() on bytes returns a list of bytes where each token is the substring. However, when we call enumerate(s) on a bytes object s, we get integer values for each byte. That's fine.
Now, we should consider: what if the string contains characters other than '#' and '.'? Not per constraints.
Now, final solution.
But let's double-check if there is any case where the count of days might be different due to the fact that after training they might try to jump differently? For instance, after training to jump L, when they come back, they might attempt to jump over multiple boards at once? But the description: "they are able to only see how far ahead is the next floorboard." So at each point, they only know the distance to the next board. So they can't plan to skip because they don't know if there is a board further. So they must land on the next visible board. That's deterministic.
Thus correct.
Now, we can also think about this problem in terms of increasing gaps. So answer is number of record gaps.
Therefore final answer.
Now, produce final output. ```python
import sys
def main():
# read all input, split by whitespace (lines)
data = sys.stdin.buffer.read().split()
if not data:
return
t = int(data[0])
out = bytearray()
idx = 1
for _ in range(t):
s = data[idx] # bytes object containing only '#' and '.'
idx += 1
prev = -1 # index of previous '#'
max_gap = 1 # current maximum jump capability
days = 0
# scan the string
for i, c in enumerate(s):
if c == 35: # ord('#') == 35
if prev != -1:
gap = i - prev
if gap > max_gap:
days += 1
max_gap = gap
prev = i
out.extend(str(days).encode())
out.append(10) # newline
sys.stdout.buffer.write(out)
if name == "main":
main()