Prateek wants to give a party to his N friends on his birthday, where each friend is numbered from 1 to N. His friends are asking for a gift to come to the party, instead of giving him one. The cost of the gifts are given in the array Value where i^th friend asks for a gift which has a cost Costi.
But, Prateek has only X amount of money to spend on gifts and he wants to invite his friends which are in continuous range such that sum of the cost of the gifts of those friends will be exactly equal to X.
If he can invite his friends, who can satisfy the above condition then, print YES otherwise print NO.
Input:
The first line contains a single integer T, denoting the number of test cases. In each test case, the following input will be present:
The next line contains two space-separated integers N and X, where N represents the number of friends and X represents amount of money which Prateek can spend on gifts.
Next N line contains N integers, where i^th line contains i^th integer, which represents the Costi .
Ouput
Output exactly T lines, each containing the answer to the corresponding test case .
Constraints:
1 ≤ T ≤ 10
1 ≤ N , Costi ≤ 10^6
1 ≤ X ≤ 10^12
SAMPLE INPUT
1
5 12
1
3
4
5
2
SAMPLE OUTPUT
YES
Explanation
In the sample input, T is equal to 1. So, accordingly, in next line, values of N and X are given which are 5 and 12 respectively. In the next 5 lines, you have costi asked by i^th friend. As friends numbered from 2 to 4 (inclusively) have gifts value which are {3, 4, 5}, and their sum equals to 12 - that is, the given value of X. So, the answer is YES.
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 need to understand the problem: Given N and X, and an array of N costs (each on its own line? Actually "Next N line contains N integers, where i^th line contains i^th integer, which represents the Costi." So it seems each line has a single integer, i.e., the array values. So we have an array A of size N. Need to check if there exists a contiguous subarray whose sum equals exactly X. Output YES or NO per test case.
Constraints: N up to 1e6 per test case, T up to 10, X up to 1e12, Costi up to 1e6. So we need an O(N) or O(N log N) algorithm per test case. Since we need to check for exact sum, sliding window technique works because all costs are positive? Are costs positive? The problem says "1 ≤ N , Costi ≤ 10^6". It says "1 ≤ N , Costi ≤ 10^6". That is ambiguous: Usually they'd write 1 ≤ N ≤ 10^6, 1 ≤ Costi ≤ 10^6. So yes, costs are positive integers. So the array has only positive numbers. Therefore we can use the two-pointer sliding window to find if any subarray sum equals X. Since all are positive, when we move left pointer forward, sum decreases; moving right pointer forward increases sum. So we can maintain a window [l, r] and its sum. Expand r until sum >= X, then if sum == X -> YES. If sum > X, move l forward (shrink). Continue until r reaches N. Complexity O(N).
But careful: X can be up to 1e12, and sum of N values up to N*1e6 = 1e12 (since N up to 1e6, product = 1e12). So 64-bit integer needed.
We need to read input efficiently: Use sys.stdin.read() or fast I/O.
Edge cases: If X == 0? But constraints say 1 ≤ X ≤ 10^12, so X at least 1. Also N ≥ 1. So fine.
Now about sample: N=5, X=12, costs: 1,3,4,5,2. Subarray from index 2 to 4 (1-indexed) sums to 12 -> YES.
Implementation details: For each test case, read N, X; then read N integers. Use sliding window.
Pseudo:
def has_subarray_sum(arr, X):
n = len(arr)
l = 0
cur = 0
for r in range(n):
cur += arr[r]
while cur > X and l <= r:
cur -= arr[l]
l += 1
if cur == X:
return True
return False
Since all positive, while loop ensures we shrink until cur <= X.
But note: arr may have large values > X, but that's okay: we add it, cur > X, then while loop shrinks. However if a single element > X, after adding it, cur > X, we will shrink from left until l > r? Actually after adding that element, l is at previous start, cur > X, we then subtract arr[l] until l <= r. Since cur > X, we subtract arr[l] repeatedly. When l becomes r+1, cur would be 0? Let's simulate: If arr[r] > X, after adding, cur = arr[r] > X. Then while cur > X and l <= r: subtract arr[l]; but l initially maybe 0, so subtract arr[0], then if after subtraction still cur > X? Actually if we only subtract the earlier elements, but arr[r] alone might be > X, even after subtracting all previous ones, when l becomes r, cur = arr[r] still > X. Then condition: while cur > X and l <= r: subtract arr[l]; l increments to r+1, cur becomes 0? Actually careful: if l == r, then cur = arr[r] > X. We still have cur > X and l <= r (l == r). So enter loop: cur -= arr[l] i.e., subtract arr[r] from itself, cur becomes 0; l becomes r+1. Now loop condition: cur > X? 0 > X? No, break. So then after loop, check if cur == X? 0 != X unless X=0, but not. So we continue. Then next r increments, and we add next element, etc. That works.
So algorithm is correct.
We must handle multiple test cases.
Complexities: O(total N) across all test cases.
Now we need to output YES or NO per test case.
Check constraints: T up to 10, total N across T maybe up to 10^7? Actually per test case N up to 10^6, T up to 10, so total up to 10^7, which is fine for O(N). Memory: need to store array of up to 1e6 integers per test case; we could read all at once but may just process as we read, but we need to use sliding window which requires sequential access. So we can read all ints at once and then iterate. However easier: we can read line by line using sys.stdin.buffer. But reading 1e6 numbers line by line in Python might be a bit slow but still okay if using fast I/O. I'd use sys.stdin.buffer.read() to read all bytes and map to integers. Then parse.
Implementation approach:
import sys
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
n = int(next(it))
x = int(next(it))
# read n costs
arr = [0] * n
for i in range(n):
arr[i] = int(next(it))
# sliding window
cur_sum = 0
l = 0
found = False
for r in range(n):
cur_sum += arr[r]
while cur_sum > x and l <= r:
cur_sum -= arr[l]
l += 1
if cur_sum == x:
found = True
break
out.append("YES" if found else "NO")
sys.stdout.write("\n".join(out))
if name == "main":
main()
But note: The input format says "Next N line contains N integers, where i^th line contains i^th integer". That means each cost is on a separate line. However using split reading all whitespace works fine regardless of line breaks.
Edge Cases: If X is huge ( > total sum ), then no subarray can sum to X. The algorithm will go through all r, cur_sum will be total sum at end, but it will not exceed X because it's less; but we only check while cur_sum > x; that never triggers; then at final cur_sum might be < x, so not found. So output NO.
Now verify correctness on sample.
Sample Input:
1
5 12
1
3
4
5
2
Our reading: after T=1, then next two ints: 5 12, then 5 ints: 1,3,4,5,2. Process: sliding window:
r=0: cur=1, not >12, check equal? no.
r=1: cur=4, no.
r=2: cur=8, no.
r=3: cur=13 >12 -> while: subtract arr[0] (1) => cur=12, l=1 -> check equal? yes -> found. Output YES.
Works.
Now note: The problem statement: "The cost of the gifts are given in the array Value where i^th friend asks for a gift which has a cost Costi." And then "Next N line contains N integers, where i^th line contains i^th integer, which represents the Costi." It seems ambiguous: maybe the array is given as N lines each with a single integer, which we assumed. So our parsing works.
Complexity: O(N) per test case, memory O(N) for the array. Could also use generator to avoid storing entire array? But we need array for sliding window when we subtract from left; but we only need to access arr[l] when l moves. Since we process sequentially, we can just store the array in a list; it's fine.
Alternative: We can read costs as we go and maintain a queue? But we need to subtract earlier elements, so we need to know the values that are at the left of the window. Since we are only moving l forward, we can store the entire array, or we could store a list of costs anyway.
Memory: max N = 1e6, integers in Python take about 28 bytes each, so ~28 MB, okay.
But T up to 10, but we process test cases one by one, so only one array at a time, so memory OK.
Now, we should also consider possibility that there are multiple test cases and total input size up to maybe 10 million numbers, reading all into memory at once might be heavy: each number as string bytes, but it's okay for 10 million? 10 million tokens maybe around 80 MB (each token maybe a few bytes), but overall maybe okay. But could be near memory limit? Usually problems allow up to 256 MB. I think it's fine. But to be safe, we could process test cases while reading incrementally using sys.stdin.buffer.readline(). But using split might read all at once, but for T=10 and N=1e6 each, that's 10 million numbers plus T and N values, which is ~10 million * average 7 bytes = 70 MB, plus overhead of list of byte strings. Might be borderline but likely acceptable. However we can implement reading line by line for each cost to reduce memory.
But the simpler method: Use sys.stdin.buffer.read() then split; it's typical for CP in Python. It's okay.
But note: 10 million numbers plus overhead of list of 10 million Python bytes objects: each bytes object overhead maybe 33 bytes? That would be huge (330 MB). Actually the .split() returns a list of byte strings. Each byte string is a separate Python object with overhead. So for large input, that could be memory heavy. For 10 million tokens, memory would blow. So better to use an iterator that reads line by line and converts to int on the fly.
We can design a fast generator: Use sys.stdin.buffer.readline() in a loop. Since each line is one integer for costs, we can just read them line by line.
But reading 10 million lines with .readline() in Python is okay but may be slower; but still plausible with buffering.
Alternative: Use sys.stdin.buffer.read().split() but memory issue. However typical problems on platforms like CodeChef might allow this? But with N up to 1e6 and T up to 10, total tokens = 2T + sum(N) + T? Actually each test case: N and X (2 numbers) + N costs = N+2 tokens. For T=10, max N per test 1e6, total tokens up to 10(1e6+2)= ~10 million. A list of 10 million byte strings will indeed use a lot of memory, maybe >500 MB, causing MemoryError. So better avoid storing all tokens.
Thus we should process test cases reading line by line.
We'll implement using sys.stdin.buffer.readline to read N and X, then for i in range(N): cost = int(sys.stdin.buffer.readline()) and store in array. But then we need to store array anyway for sliding window. That's fine: array of ints (Python objects) of size 1e6 is ~28 MB, which is acceptable. The line-by-line reading will parse each line as int and store. That may be slower but okay. For 10 million lines, reading line by line with .readline() might be okay within time limit? Usually Python can handle about 10-20 million lines in a few seconds? It might be borderline but likely acceptable given typical time limits (like 1-2 seconds? Possibly not). For worst-case T=10, N=1e6 each, that's 10 million lines, plus T lines for test case count and N X lines. That's a lot. We might need to optimize I/O further.
We can use sys.stdin.buffer.read() but parse incrementally without storing all tokens as a list. For example, we can read all bytes and then parse integers manually using a fast integer parser that yields one integer at a time. That would avoid storing the byte strings. But implementing that manually might be overkill.
Alternatively, we can use sys.stdin.buffer.read().split() but we can free memory after each test case? The whole list is created at once, but if we process test cases sequentially, we could read all data first, then parse. But the list of tokens is already in memory, so memory usage high.
Maybe the problem expects solution in C/C++? But we need to provide Python solution.
But perhaps the constraints for N are not that high for Python? On many platforms, N up to 10^5 is typical for Python; but here it's 10^6. Still doable with careful I/O and O(N) algorithm. However we must be careful with memory.
We can use array module or list of ints; the list of ints uses Python objects; memory ~28 MB per 1e6, okay. For 1e6, it's 28 MB. For T=10 sequentially, we allocate and deallocate per test case, so memory not cumulative. The main memory issue is the token list if we use .split(). So we avoid that.
Using sys.stdin.buffer.readline() for each cost: For 1e6 lines, it's about 1e6 readline calls. Each call reads a line; overhead maybe acceptable, but we need to convert to int each time. We can speed up by reading a large chunk and parsing? But likely fine.
Better: Use sys.stdin.buffer.read() but then use map(int, data.split())? That's the same memory issue. So we go with line by line.
But wait: The input format says "Next N line contains N integers, where i^th line contains i^th integer". That means each cost is on its own line. So there are exactly N lines after the N X line. So reading line by line is natural.
We'll implement as:
import sys
def solve():
import sys
data = sys.stdin.buffer
t = int(data.readline())
out_lines = []
for _ in range(t):
line = data.readline()
while line.strip() == b'':
line = data.readline()
n_x = line.split()
if len(n_x) == 0:
# maybe blank line? just skip
line = data.readline()
n_x = line.split()
n = int(n_x[0]); x = int(n_x[1])
arr = [0]*n
for i in range(n):
# some lines may be empty? but shouldn't
val = int(data.readline())
arr[i] = val
# sliding window
cur = 0
l = 0
found = False
for r in range(n):
cur += arr[r]
while cur > x and l <= r:
cur -= arr[l]
l += 1
if cur == x:
found = True
break
out_lines.append("YES" if found else "NO")
sys.stdout.write("\n".join(out_lines))
if name == "main":
solve()
But we need to consider that after reading N and X line, the next N lines each contain a single integer. However sometimes there may be leading/trailing spaces. Using int(data.readline()) will handle whitespace.
Potential performance: reading 10 million lines with data.readline() is okay? Let's test mentally: In Python, reading 10 million lines from sys.stdin.buffer may be a bit slow but possibly within 2-3 seconds? Actually reading 10 million lines of short numbers (like up to 1e6) can be heavy: each readline call involves Python overhead. For 1e7 lines, it might be around 1-2 seconds? Actually it might be more like 5-10 seconds, depending on environment. For competitive programming with strict time limits, this might be too slow.
Thus we might want to use a faster method: read all input as bytes and parse integers manually without creating many objects. We can implement a fast integer reader that yields ints from a bytearray.
We can read the entire stdin into a bytes object (using sys.stdin.buffer.read()). That will be large: up to maybe 10 million numbers * average 7 bytes = 70 MB, plus newlines ~10 MB => 80 MB. That's a large bytes object but still within memory (80 MB) if allowed. Then we can parse integers from that bytes object without splitting into many objects. That's more memory efficient than a list of byte strings, because the bytes object is a single contiguous block. Then we can iterate over it to extract ints.
Implement a generator:
def ints_from_bytes(buffer):
num = 0
sign = 1
in_num = False
for c in buffer:
if 48 <= c <= 57: # digit
num = num*10 + (c-48)
in_num = True
else:
if in_num:
yield sign * num
num = 0
sign = 1
in_num = False
if c == 45: # minus sign (not needed as positive)
sign = -1
if in_num:
yield sign * num
Then we can do:
data = sys.stdin.buffer.read()
it = ints_from_bytes(data)
t = next(it)
...
This uses only the bytes object (80 MB) plus some overhead; memory is okay. The generator yields ints one by one, not storing all tokens. So memory peak ~80 MB for bytes + some for array (list of ints). But we also store the array of costs, which is another ~28 MB. Total maybe ~108 MB, acceptable for typical 256 MB limit. Also we process test case by test case; we can read all ints at once and then iterate over them. However note that after reading all ints, we have the entire data as ints generator; but we need to create the array for each test case. That's fine.
But careful: The generator ints_from_bytes will yield all integers in order from the entire input. So we can get t, then for each test case: n = next(it), x = next(it), then for i in range(n): arr[i] = next(it). That's efficient. The generator uses a simple loop over the bytes, which is fast in Python (since it's a loop in Python, but for 80 million bytes may be okay). But we can also use map(int, data.split()) which creates a list of byte strings then converts? That's heavy. So custom parser is better.
But maybe we can rely on sys.stdin.buffer.read().split() and accept memory overhead? Let's estimate: For 10 million numbers, splitting returns a list of 10 million byte strings. Each byte string has overhead: on 64-bit CPython, a bytes object has 33 bytes overhead (maybe 33-37) plus the length of the data. For each number, average length maybe 3-7 characters; but each bytes object also stores the characters. So total memory: overhead 33*10M = 330 MB plus data 10M * average 4 = 40 MB -> ~370 MB. That's too high. So we avoid split.
Thus the custom integer parser is advisable.
Alternative: Use sys.stdin.buffer.read().split() but then process each test case sequentially and maybe convert as needed? But still the list of tokens is created all at once, consuming huge memory. So not good.
So we'll implement a fast integer parser.
But note: In Python, there is also the possibility of using array('I') or reading via numpy? Not allowed in standard CP.
We'll implement a fast integer reading function.
Standard trick:
import sys
def fast_ints():
import sys
data = sys.stdin.buffer.read()
num = 0
sign = 1
for c in data:
if c >= 48:
num = num*10 + (c - 48)
else:
yield sign * num
num = 0
sign = 1
if c == 45: # '-'
sign = -1
yield sign * num
But careful: The above code treats any non-digit as delimiter, including newline. However it yields a number for every delimiter? Actually it yields a number each time it encounters a non-digit after reading some digits. It also yields a number at the end. But one issue: If there are multiple delimiters consecutively, it would yield zeros for each? Let's examine: When we see a non-digit and we haven't been accumulating digits (num==0, in_num false), we still yield sign * num (which is 0). That would produce extra zero numbers for each delimiter. That's not desired. So we need to track whether we are inside a number.
Better:
def fast_ints():
import sys
data = sys.stdin.buffer.read()
num = 0
sign = 1
in_num = False
for c in data:
if 48 <= c <= 57:
num = num*10 + (c - 48)
in_num = True
else:
if in_num:
yield sign * num
num = 0
sign = 1
in_num = False
if c == 45: # '-'
sign = -1
if in_num:
yield sign * num
This yields only when we have read at least one digit.
Now we can use it.
We must ensure that the input contains only positive numbers, so no negative signs.
Now we can implement:
def main():
import sys
it = fast_ints()
t = next(it)
out = []
for _ in range(t):
n = next(it)
x = next(it)
arr = [0] * n
for i in range(n):
arr[i] = next(it)
cur = 0
l = 0
found = False
for r in range(n):
cur += arr[r]
while cur > x and l <= r:
cur -= arr[l]
l += 1
if cur == x:
found = True
break
out.append("YES" if found else "NO")
sys.stdout.write("\n".join(out))
But careful: fast_ints is a generator that yields ints. We must ensure we call next(it) only when we have numbers; the input is well-formed.
Now, we need to consider that the entire input may be large; reading it all into memory as bytes may be up to 80 MB, which is okay. However we also create the arr list of ints of size up to 1e6 (28 MB). So total ~108 MB. That's acceptable.
But we must also consider that for T=10, we are allocating arr for each test case sequentially, so memory for arr is freed after each test case? Actually we reassign arr each test case; the previous list will be garbage collected, but may still occupy memory until GC runs. But Python's memory management may hold onto memory; but peak should be at most max(n) + bytes buffer. So still ~108 MB.
Alternatively, we could avoid storing the whole array if we process sliding window as we read costs? But sliding window needs to potentially subtract earlier costs when moving left pointer. If we read costs one by one, we could store them in a list anyway. But maybe we can use a deque? Still need to store because we may need to subtract earlier ones when we shrink. However we could read all costs first because we need random access? Actually sliding window only needs to subtract arr[l] when l moves. Since we process sequentially from left to right, we could read each cost, add to cur, and also append to a list. When we move l, we need to know the cost at position l. So we need to store all previous elements until they are removed. In worst case, if we never move l much (if X is large), we might end up storing all N elements. So we need O(N) storage anyway. So storing list is necessary.
Thus memory usage is fine.
Now, we need to ensure that sliding window algorithm works for large X up to 1e12. cur sum might overflow Python int? Python int arbitrary precision, so fine.
Now edge cases: X may be less than some individual element? That is handled as earlier.
But consider if X is exactly the sum of all elements. Then we will eventually get cur == X at r = N-1, after possibly shrinking? Since cur sum total = total sum, and if total sum == X, then at r = N-1, cur will be total sum. Then we will check while cur > X: not true if equal, so then check cur == X -> YES. So works.
Now, what if there are multiple test cases with varying N. Our fast_ints generator yields all ints from entire input; we iterate over test cases using next(it). That's fine.
Now, we should test with sample.
But one more nuance: The problem statement says: "Next N line contains N integers, where i^th line contains i^th integer". That implies each line has a single integer. However our integer parser from the entire buffer doesn't care about lines. So it's fine.
Potential pitfalls: The input might have trailing spaces/newlines. Our parser handles that.
Now, we should also consider that T lines might have extra blank lines? Usually not.
Now, we need to ensure that for large input, the generator fast_ints is efficient. The for loop over data (bytes) and arithmetic are in Python, so might be a bit slower but still okay for 80 million bytes (since total bytes ~80M). Loop over 80M bytes in Python may take ~0.5-1 seconds? Actually Python loops are slower; 80M iterations could take a few seconds (maybe 2-3 seconds). But we also have the sliding window loop over up to 10M elements. So total could be 5-8 seconds. That might be near time limit. We could optimize the integer parser further by using memoryview or using built-in methods? Possibly we can use the built-in map(int, sys.stdin.buffer.read().split()) which is implemented in C and is faster, despite memory overhead of list? Actually map returns an iterator; but the split() still creates a list of byte strings. That list creation uses memory but also time. However the split() in C is fast, but the creation of many bytes objects might be heavy both in time and memory. But perhaps for 10M tokens, it could still be fast if memory is available? But memory may exceed limit.
We can test typical behavior: On CodeChef or similar, many Python solutions use sys.stdin.buffer.read().split() for up to 2 million tokens. For 10 million, memory may be too high. So better to avoid.
Another approach: Use sys.stdin.buffer.readline() in a loop but accelerate by reading large chunks? Actually reading line by line is implemented in C, each call is fast. But for 10 million lines, the overhead of Python function calls is large. But we can maybe use sys.stdin.buffer.read().split() and accept memory? Let's evaluate memory: 10M tokens, each token as bytes object. In CPython, each bytes object overhead is about 33 bytes + size of data. For numbers up to 1e6, length up to 7. Average maybe 4? So overhead ~37 bytes per token. So total ~370 MB. That likely exceeds typical memory limit (256 MB). So not acceptable.
Therefore custom parser is better.
But we can also use the method: read all bytes, then convert to array of ints using numpy? Not allowed.
We can implement an even faster integer parser using re.finditer? Not great.
Maybe we can read and process test cases on the fly, without storing entire input as bytes. For each test case, we read N and X via readline, then read N lines, but we can read each line, convert to int, and directly add to sliding window? Actually we need to store the array for potential later subtraction. But we can store only the necessary part: we need to know the costs that are still in the window. Since we process sequentially, we could store costs in a list as we go, but we also need to be able to remove from front when we move left pointer. We could use a deque to store costs of the current window? But we also need to know the sum of current window; we can compute sum as we go. However the challenge: When we advance r, we add the new cost. When we need to shrink, we pop from left of the deque. This works. And we don't need to store all previous costs that have been removed. So we can avoid storing the entire array; we only need to store the current window? But wait: In sliding window algorithm, we need to subtract arr[l] when we move left. That's exactly what deque does. However, do we need to know the full array to compute future windows? No, because we only ever access elements at the left of the current window, and we only ever add elements as we read them. So we can read costs one by one, maintain a deque (or list with left index) of the current window. But we also need to know the values that we have removed? No. So we can process streaming: For each cost read, we add it to cur and append it to the deque. Then while cur > X, we pop left from deque, subtract from cur. Then if cur == X, we can break early. If we break early, we still need to skip reading the remaining costs for that test case? That would be tricky because the input is line-oriented; we would need to consume the rest of the lines for that test case to proceed to the next test case. But we can simply read and discard them. That's acceptable.
Thus we can avoid storing the whole array. This reduces memory to O(N) only for the worst-case window size, which could be up to N if X >= total sum. But that's the same as storing the whole array. However we could also avoid storing the whole array by using a queue that stores only the current window. In worst case, the window might encompass the entire array (if we never shrink because sum never exceeds X). But if X is huge, say X > total sum, we will never have cur > X, so we never pop left; the window will grow to include all elements. So we will end up storing all N elements anyway. So worst-case memory still O(N). But it's same as before. However we can avoid storing the entire array from the beginning; we store them as we read. But still, we may have to store all N if X is large. So memory is similar.
But the advantage is we don't need to first read all N costs into a list then process; we can process as we read. That might reduce the need to allocate a large list? Actually we would still need a data structure to store the window elements. In Python, a collections.deque is a good choice, but a deque also stores elements as Python objects in a linked list of blocks. The memory overhead might be higher than a list? But maybe comparable.
If we use a list and maintain left pointer index, we can still store only the elements we have read; but we need to discard elements that are before left pointer to free memory. However Python list does not automatically shrink from front; we could use a deque or we could use a custom circular buffer. Simpler: Use deque.
But reading line by line may be okay for 10M lines? Let's evaluate performance: reading line by line and processing in Python might be borderline but might pass with optimized code. However, using fast_ints from a single read might be more efficient because it's a single pass over the bytes with less Python overhead per number? Actually both involve a Python loop per number. In fast_ints, we have a for loop over bytes, and inside we do digit conversion. That's a loop over each character, not each number. For each number, we have a few operations per digit. That's about the same overhead as reading a line and converting with int() which also parses digits. However the difference: reading line by line calls readline which involves scanning for newline each time; that is done in C, but then we call int() which parses the string. So the per-number overhead is a C function for reading line and a C function for parsing int? Actually int() in Python will parse a string object, which is also implemented in C. So each number incurs Python overhead for creating the string object from the line (the bytes object) and then converting. That overhead may be substantial for 10M lines. However if we use fast_ints, we avoid creating intermediate bytes objects; we parse digits directly from the bytearray and produce ints. So fast_ints might be faster.
But we also have the sliding window loop; that's another Python loop over N elements. So total Python loops: one for parsing (if we parse manually) and one for sliding window. That's two loops. With line-by-line reading, we combine the reading and processing: we read a number, then immediately process it (add to window). So there is only one loop over N elements (plus overhead of readline). But readline is a C function; the Python code calls readline which returns a bytes object, then we call int(), then process. So per iteration we have Python call overhead but still one loop. The fast_ints approach has two loops: first a loop over all bytes to parse ints, storing them possibly in a list, then a second loop over the list for sliding window. That's two passes. However we can combine them by processing ints as we parse from the bytes, similar to reading line by line but with custom parser. We could adapt fast_ints to yield ints, and in the main loop, we process each int for the current test case as we go, without storing the entire array. That would be a single pass over the bytes and a single pass over the numbers? Actually it would be one pass over bytes, and for each number we process it for sliding window (if we are in the cost-reading phase). That could be more efficient: we read all bytes once, parse ints sequentially, and for each test case we read N and X, then for i in range(N): cost = next_int, process it immediately in sliding window. That eliminates storing the array and also eliminates the separate sliding window loop. The sliding window processing is interleaved with parsing. So we have a single loop over the N numbers (plus loop over bytes but that's the same as parsing). Actually the parsing loop is over bytes, not numbers; but we can process numbers as they are parsed. This could be done by writing a state machine: we parse all ints but we know the structure: first int T, then for each test case: N, X, then N costs. As we parse each int, we can directly feed into the sliding window logic for that test case.
We can design a parser that reads bytes and processes on the fly. That is efficient.
We can implement a custom solution:
Read entire input into a bytes object.
Use index pointer to scan through the bytes.
Define function next_int() that reads next integer from the bytes and advances pointer.
Then in Python, we can have a while loop for test cases.
But we need to implement the sliding window as we read each cost.
Implementation plan:
def solve():
import sys
data = sys.stdin.buffer.read()
n = len(data)
i = 0
# helper to get next int
def next_int():
nonlocal i
# skip non-digit (but we assume we are at start of int)
# actually we should skip any non-digit characters (like newline, space) before reading number
while i < n and data[i] <= 32: # skip whitespace (space, newline, tab)
i += 1
num = 0
while i < n and 48 <= data[i] <= 57:
num = num * 10 + (data[i] - 48)
i += 1
return num
code
t = next_int()
out = []
for _ in range(t):
N = next_int()
X = next_int()
# sliding window variables
cur_sum = 0
left_sum = 0 # but we need to store the window elements? Actually we need to subtract arr[l] when moving left. Without storing the array, we need to know the values that are in the window. We can store them in a deque.
# We'll use a deque to store the current window's values.
from collections import deque
window = deque()
found = False
for _ in range(N):
val = next_int()
cur_sum += val
window.append(val)
while cur_sum > X and window:
cur_sum -= window.popleft()
if cur_sum == X:
found = True
# but we still need to consume remaining numbers of this test case? We can break out, but then we must still advance the pointer to skip the remaining numbers. However we are in a loop reading N numbers; if we break early, we will not have consumed the rest, causing the next test case to read from wrong position.
# So we must continue reading all N numbers regardless.
# We can set found flag but continue reading without processing? Actually we still need to read them to advance pointer, but we don't need to process them for the window because we already know answer YES. However if we skip processing, we might have leftover numbers that would be misinterpreted as next test case. So we must read and discard them. But we are already in a loop that reads exactly N numbers. So we can't break out of the loop because we need to consume all N numbers. So we continue, but we could stop updating the window (since answer already found) to save work, but we must still call next_int() for each remaining cost to advance pointer. So we can add a condition: if not found: process; else: just read and discard (call next_int) but don't add to window. However the loop is set to read N numbers; we are inside it calling next_int. So we can structure as: for j in range(N): val = next_int(); if not found: process as above; else: pass. That's fine.
out.append("YES" if found else "NO")
sys.stdout.write("\n".join(out))
But careful: In the case where we break early (found True), we still need to read the remaining numbers of this test case. The above structure with a for loop that always calls next_int() for each of the N numbers is fine. However we need to ensure that in the "found" branch we don't add to window, and we don't modify cur_sum, etc. That's okay.
But we also need to consider that if we found early and then we stop updating cur_sum and window, the window and cur_sum become stale, but we are not using them later. So fine.
However, there's a nuance: The sliding window algorithm relies on maintaining the correct window and cur_sum for the subarray ending at each r. If we stop updating after found, we may have a stale state but we are not going to use it. So it's okay.
But what about the case where found becomes true later? Actually if we stop processing, we might miss that we could have found earlier? No, we are already found, answer is YES, no need to check further.
Thus this approach works and avoids storing all costs.
But note: We still use a deque to store the current window. In worst-case, if X is large and we never find, we will store all N elements in the deque. That's still O(N) memory. But it's the same as before. However we don't store the array separately; the deque holds the window. For worst-case (no subarray sum equals X and X >= total sum), the window will contain all elements, so deque size = N. So memory usage same. But we avoid an extra list. The deque uses a linked list of blocks, which may have overhead but likely similar.
Now, the main advantage is that we only have one pass over the data (parsing and processing combined) and we avoid creating an intermediate list of ints. This should be faster and memory-efficient.
But we must be careful about the while loop skipping whitespace: we need to handle spaces and newlines. The condition data[i] <= 32 may be okay because digits have ascii >=48, spaces (32), newline (10), carriage return (13) are less. So we skip them. This ensures we land on the next digit.
Edge: There might be no trailing whitespace, but after the last number we might have EOF. The while loops handle.
Now, potential issues: The deque's popleft is O(1). That's fine.
Now, let's test mental with sample.
Input as bytes: "1\n5 12\n1\n3\n4\n5\n2\n" (maybe no trailing newline). Parse:
t=1
N=5, X=12
Now loop j=0: val=1, cur_sum=1, window=[1], while cur_sum>12? no, check ==? no.
j=1: val=3, cur_sum=4, window=[1,3], not >12, !=12.
j=2: val=4, cur_sum=8, window=[1,3,4], !=12.
j=3: val=5, cur_sum=13, window=[1,3,4,5], while cur_sum>12: pop left (1) => cur_sum=12, window=[3,4,5]. Now cur_sum==12 -> found=True.
j=4: val=2, but found is True, we just read val and discard (no processing). Loop ends. Output YES.
Works.
Now we need to ensure that after found, we still need to read the remaining numbers. In the above, we read val=2 by calling next_int(). That's good. But note: The next_int() function advances i based on the bytes. In the loop we always call val = next_int() exactly N times. So after reading all N numbers, i will be positioned at the start of next test case or EOF.
Now, ensure that after reading all test cases, we don't have leftover data.
Potential pitfalls: If we break early inside the while loops? Actually we don't break; we continue to next iteration. But what if we want to break to save time? Not needed; we just read remaining numbers which is fine.
But we must be careful about the while loop inside the processing: while cur_sum > X and window: we pop left. This ensures we shrink. But after we found and we stop processing subsequent numbers, we don't update window or cur_sum. That's fine.
Now, about the deque: import inside function; may cause overhead but okay.
Now, one more optimization: We can avoid using deque if we store the window values in a list and maintain left index. However we would need to store all read values because we cannot discard from front of list without slicing (which is O(N)). So better to use deque.
Alternatively, we can implement a custom queue using a list with two pointers (head and tail) and store values in a preallocated list of size N? But we don't know N until we read it; we could allocate list of size N after reading N? But then we are back to storing all values. However using deque is fine.
But note: Python's deque for large N may have high memory overhead due to its block structure (each block holds 64 items). Memory overhead per element may be less than list? Actually list stores pointers to Python objects; each element is a Python int object (28 bytes) plus list pointer (8 bytes) -> about 36 bytes per element. Deque stores the same Python int objects, plus overhead of block structure: each block is an array of 64 PyObject*; so per element overhead similar to list but with extra block headers. Roughly comparable.
We could avoid storing the elements altogether if we used the sliding window approach with two pointers but we need to know the values at left when we move left. Since we process sequentially, we could store the array values in a list anyway; but we might try to compute sums without storing? Not possible. So we need to store the window.
But we can also use a variable to store the sum and left pointer index; we still need to know the values that have been added to the window but not yet removed. So we need to store them. So deque or list with left index is needed.
We could use an array of ints from the array module? Not necessary.
Thus the approach is okay.
Now, about performance: The custom parser with while loops and deque operations for 10M numbers might be fast enough. Let's analyze time: For each number, we have:
In parser: skip whitespace (maybe a few chars), then read digits (average maybe 3-7). So per number maybe 5-10 loop iterations of the parser's inner while. Each iteration simple arithmetic. So total character iterations = total bytes ~80M, so about 80M iterations. That's fine.
For each number (N total), we do some Python operations: adding to cur_sum, appending to deque, while loop for shrinking (which may pop multiple times). In worst-case, each element is pushed and popped at most once, so total operations O(N). So overall about 2*N operations. So total operations maybe 200M simple Python steps. That might be near the limit but might still pass with PyPy (which is often used). The problem likely expects PyPy? Many CP platforms use PyPy for Python. So we can aim for PyPy, which is faster for loops.
We can consider further optimization: Use list with left index (head) and tail, but then we need to store all values anyway. But we can implement a circular buffer using a list of size N and two pointers; that would avoid overhead of deque's block allocations. But it's a bit more code but doable.
Simplify: Use a list to store all values (arr) and left pointer index; we don't need to pop, just increment left and subtract arr[left-1]? Actually typical sliding window with list:
arr = [0]*N
l = 0
cur = 0
found = False
for r in range(N):
cur += arr[r]
while cur > X:
cur -= arr[l]
l += 1
if cur == X:
found = True
break
Here arr is stored. So we need to read all costs into arr first. That's similar to earlier but we can avoid storing all if we break early? But we still need arr for future subtraction if we haven't broken? Actually if we break early when found, we don't need the rest. So we can read numbers one by one, store them in a list, but if we break early we might not have read all; but we still need to consume the rest. So it's easier to use deque.
Let's stick with deque.
But we must be careful: The deque will store all numbers if we never shrink sufficiently. However, if we break early after found, we stop adding to deque? Actually if found, we still read the remaining numbers but we do not add them to deque (we skip processing). So the deque size at found time is at most the window size, which could be less than N. So memory may be less in successful cases.
If not found, we will end up storing all numbers (since window may be all numbers). That's worst-case. But it's the same as storing array.
Thus memory usage is similar.
Now, I'll implement the fast parsing with a custom scanner class for clarity.
Implementation details:
class FastScanner:
def init(self, data):
self.data = data
self.n = len(data)
self.pos = 0
def next_int(self):
# skip non-digit
while self.pos < self.n and self.data[self.pos] <= 32:
self.pos += 1
num = 0
while self.pos < self.n and 48 <= self.data[self.pos] <= 57:
num = num * 10 + (self.data[self.pos] - 48)
self.pos += 1
return num
But we need to be careful: There might be negative numbers? Not according to constraints.
Now, we will read the whole input:
data = sys.stdin.buffer.read()
sc = FastScanner(data)
t = sc.next_int()
...
Now, we need to import deque inside the loop. To reduce overhead, we can import collections.deque once at top.
Now, the sliding window with deque:
from collections import deque
...
for _ in range(t):
N = sc.next_int()
X = sc.next_int()
window = deque()
cur = 0
found = False
for i in range(N):
val = sc.next_int()
if not found:
cur += val
window.append(val)
while cur > X:
cur -= window.popleft()
if cur == X:
found = True
# else: just skip (val read already consumed)
out.append("YES" if found else "NO")
Case: N=1, X=6, cost=5 => cur=5, not >, not equals -> NO.
Case: N=3, costs= [1,2,3], X=6 => YES.
Case: X huge 1e12, costs sum less, never equals, after all, cur < X, while never triggered, window contains all, found false -> NO.
Case: X=0 not possible.
Case: X very small: e.g., N=3, costs=[100,1,2], X=1 => at r=1, cur=101, while cur>1: pop left: subtract 100, cur=1, window now [1] (actually after pop, window contains only the 1? Let's simulate: Initially window empty, cur=0. r=0: val=100, cur=100, window=[100]; cur>1 => while: pop left, cur=0, window=[]; cur==1? no. r=1: val=1, cur=1, window=[1]; cur==1 => found. Works.
Now, ensure while loop condition: while cur > X and window: (we must check window not empty, though if window empty cur should be 0, but cur > X could be true if X negative? Not possible. But just for safety, we can do while cur > X: but if window empty, cur would be 0, not > X. However if we popped all elements and cur still > X? That can't happen because cur is sum of elements in window, so if window empty cur=0. So while cur > X is sufficient. But we need to ensure we don't call popleft on empty deque; but if cur > X and window is empty? That can't happen because cur is sum of window, if window empty cur=0, can't be > X>=1. So safe. So we can use while cur > X: cur -= window.popleft().
But what if X is 0? Not allowed. So fine.
Now, we need to consider that after found=True, we still call sc.next_int() for the remaining numbers of the test case. That will correctly advance pointer. But what about the case where we break early but there are still numbers to read? We don't break the for loop; we continue until i reaches N. So that's fine.
Now, we need to ensure that after found, we do not do any operations that might affect correctness, but we only need to read the numbers. So we skip processing.
Potential bug: In the case where found becomes true at some r, and then later numbers are read but not processed, the window and cur remain as they were at the moment found. That's fine. But we need to ensure that the reading of subsequent numbers still advances the pointer correctly. The call sc.next_int() will read the next integer from the byte array. So after the loop, we are at the position after the last cost. Then next test case starts reading N and X. Good.
Now, check if there are any blank lines between test cases? The problem statement doesn't mention, so likely not.
Now, we should also consider the possibility that there are extra spaces after numbers? The skip while condition (data[pos] <= 32) will skip spaces, tabs, newlines, etc. So fine.
Now, let's think about performance: The while loops in next_int are scanning characters; we use Python integer operations, which are fast. The total number of character iterations is the length of the input. For 10M numbers with average 6 digits, plus spaces/newlines, that's about 70-80 million characters. Python can process that in a loop in maybe 0.3-0.5 seconds? Actually in CP, using similar fast I/O, it's common to handle 10^7 ints within 2 seconds in PyPy. So should be okay.
But we also have the sliding window operations, which are similar.
Thus overall solution should be efficient.
Now, we need to write final answer.
I'll produce final code with proper imports and a main function.
One more nuance: The input may have N up to 10^6, but X up to 10^12, which fits in Python int.
Now, consider if there is a case where subarray sum exactly X but we might miss due to using deque and shrinking? Let's verify algorithm correctness: Since all numbers positive, sliding window that maintains the smallest l such that sum[l..r] <= X works. At each r, after shrinking, sum[l..r] <= X. If any subarray sum equals X, there exists an r where sum[l'..r] = X for some l'. At that r, after processing, our window may have l that is <= l'? Actually we need to prove that we will encounter cur == X. Standard two-pointer approach: For each r, we maintain the largest l such that sum[l..r] <= X? Actually we shrink until sum <= X, so after the while, we have the smallest l (or the largest? Let's think: initially l=0. We add arr[r]. Then while sum > X, we increment l and subtract arr[l-1]. So after loop, sum[l..r] <= X. Moreover, before incrementing l, sum[l..r] > X; after incrementing, sum[l+1..r] <= X. So we have the smallest l such that sum[l..r] <= X? Actually if we increment l until sum <= X, we are increasing l until the sum becomes <= X. So the resulting l is the smallest index such that sum[l..r] <= X? Let's test: Suppose arr = [2,3,5], X=8. At r=0: sum=2 <=8, l=0. r=1: sum=5 <=8, l=0. r=2: sum=10 >8, so we increment l to 1, sum=8 <=8. So after processing, l=1, sum=8. So we found equality. So it works.
If there is subarray sum = X, say from L to R. At r = R, before shrinking, sum[0..R] >= X (since all positives). As we shrink l from 0 upwards, we will eventually reach l = L because sum[L..R] = X <= X, and for any l < L, sum[l..R] > X? Not necessarily; if there are zeros, but no zeros; all positive, so sum[l..R] > sum[L..R] for l<L because we add extra positive numbers. So indeed sum[l..R] > X for l<L. So when we shrink, we will stop at l = L, and cur will equal X. So algorithm correct.
Thus final answer.
Now, about using deque: we need to import collections. We'll do at top.
Now, we need to output each answer on its own line.
Now, we need to handle large recursion? Not used.
Now, we produce final solution.
But before finalizing, we should consider potential integer overflow? Python fine.
Now, test with some cases:
Case: T=2
N=3 X=3 costs: 1 1 1 -> no subarray sum 3? 1+1+1=3 -> YES. So output YES.
N=2 X=5 costs: 2 2 -> NO.
Input:
2
3 3
1
1
1
2 5
2
2
Our code: first T=2, then read 3 3, then read three ints: 1,1,1. Process: r0: cur=1, no; r1: cur=2, no; r2: cur=3, no while, check equal -> YES. found=True, then after loop, output YES. Then next test: N=2 X=5, read two ints: 2,2. Process: r0: cur=2; r1: cur=4; after loop cur=4 !=5, not found. So output NO. So lines: YES\nNO.
Works.
Now, check for case where we need to shrink multiple times: Example: N=4, X=7, costs: 8,1,2,6 -> subarray 1,2,? Actually 1+2+? Not 7. But check: At r0: cur=8>7, while: pop left -> cur=0, l=1, window empty? Actually after pop, window empty, cur=0? Let's simulate with deque: Initially window empty, cur=0. r0: val=8, cur=8, window=[8]; while cur>7: pop left -> cur=0, window=[]; check cur==7? no. r1: val=1, cur=1, window=[1]; no while; no eq. r2: val=2, cur=3, window=[1,2]; no eq. r3: val=6, cur=9, window=[1,2,6]; while cur>7: pop left (1) -> cur=8, window=[2,6]; still >7, pop left (2) -> cur=6, window=[6]; now cur=6<=7; check eq? no. So not found. Actually there is subarray? 1+6=7? But indices: costs[1]=1? Actually 1 is at index 1 (0-based), 6 at index 3, sum=7. Our window didn't capture that because at r3 after adding 6, we had window [1,2,6] and sum=9. Then we popped 1 (sum=8), still >7, popped 2 (sum=6). Now window is [6] sum=6, which is not 7. But we missed the subarray [1,6] because when we popped 1, we also removed it, but we needed to keep 1? Let's analyze: The subarray [1,6] corresponds to l=1, r=3. At r=3, we had added 6. Before shrinking, the window covered indices from some l0 to 3. Initially l is 0? Actually we are not explicitly storing l; we use deque to represent current window from some start to r. Our algorithm after processing each r ensures that the window is the longest suffix of the prefix that has sum <= X? Wait, we need to clarify the algorithm. In standard two-pointer sliding window for positive numbers to find subarray sum equals X, we maintain l and r, and sum of window. For each r we add arr[r], then while sum > X: subtract arr[l] and l++. Then if sum == X, found. That algorithm works.
But in our implementation using deque, we are effectively doing the same: we have window deque containing elements from l to r (inclusive). We maintain cur as sum. At each new val, we append, then while cur > X: pop left (increment l). So it's identical.
Now, test with the above case using standard two-pointer:
arr = [8,1,2,6], X=7, n=4.
Initialize l=0, cur=0.
r=0: cur=8, while cur>7: cur-=arr[l] (8), l=1; cur=0, l=1. Check cur==7? no.
r=1: cur+=arr[1]=1, cur=1; while? no; check? no.
r=2: cur+=2 -> cur=3; check? no.
r=3: cur+=6 -> cur=9; while cur>7: cur-=arr[l]=arr[1]=1 -> cur=8, l=2; still >7: cur-=arr[2]=2 -> cur=6, l=3; check? no.
Now, did we ever have cur==7? No, so answer NO. Indeed there is subarray [1,6]? Let's verify indices: arr[1]=1, arr[3]=6, sum=7. But our window at r=3 after adding 6, before shrinking, we had cur=9, window indices 1..3 (1,2,6). Then we subtracted arr[1]=1 -> cur=8 (window indices 2..3). Then subtracted arr[2]=2 -> cur=6 (window index 3). We never had window [1,3]? But [1,3] is indices 1 and 3, but that is not a contiguous subarray? Actually indices 1 and 3 are not contiguous because index 2 is missing. Contiguous means consecutive indices. So [1,6] would require indices 1 and 2? Actually to include both 1 (index1) and 6 (index3), we must include index2 as well because they are not adjacent; they are separated by index2. The contiguous subarray from index1 to index3 includes indices 1,2,3 which sum to 1+2+6=9, not 7. So the subarray [1,6] is not contiguous. So correct answer is NO. So algorithm is correct.
Thus our implementation with deque replicates standard two-pointer.
Now, confirm that we handle the case where X is exactly sum of the whole array: window grows to include all, cur equals X at r=N-1, found.
Now, what about X being sum of a prefix? e.g., arr=[1,2,3], X=3, we should find at r=1 (1+2? no, 1+2=3? Actually 1+2=3 -> yes). Algorithm: r=0: cur=1; r=1: cur=3, not >, check eq -> found. Good.
Now, what about X being sum of a suffix? Works.
Now, confirm that we read all numbers correctly even if there are leading/trailing spaces. Our skip while data[pos] <= 32 will skip any whitespace. After reading a number, we will exit at the next non-digit (space or newline). Then next call to next_int will skip whitespace again. Works.
Now, we must ensure that the skip loop doesn't skip beyond EOF. While pos < n and data[pos] <= 32: pos++.
Now, we need to be careful about the case where after reading a number, we are exactly at a newline char. Next call will skip it and go to next number.
Now, what about numbers with leading zeros? Not an issue.
Now, implement.
Potential micro-optimizations: Use local variables for speed, e.g., assign data, n, pos to local variables inside next_int? But we can define as a function inside solve with nonlocal. Or we can implement as a generator of ints using while loops.
I'll implement as a class with methods for speed? Actually function call overhead might be high if we call next_int 10 million times. Better to inline the parsing in the main loop. But we can create a simple inline while loop within the main function without a separate function. That might be faster.
We can parse the entire byte array manually with an index and while loops. For each test case, we read N and X by calling a helper, but we can write the parsing code directly.
I can design it like:
def solve():
import sys
from collections import deque
data = sys.stdin.buffer.read()
nbytes = len(data)
i = 0
t = 0
# parse t
while i < nbytes and data[i] <= 32:
i += 1
while i < nbytes and 48 <= data[i] <= 57:
t = t10 + (data[i] - 48)
i += 1
out = []
for _ in range(t):
# parse N
while i < nbytes and data[i] <= 32:
i += 1
N = 0
while i < nbytes and 48 <= data[i] <= 57:
N = N10 + (data[i] - 48)
i += 1
# parse X
while i < nbytes and data[i] <= 32:
i += 1
X = 0
while i < nbytes and 48 <= data[i] <= 57:
X = X10 + (data[i] - 48)
i += 1
window = deque()
cur = 0
found = False
for _ in range(N):
# parse cost
while i < nbytes and data[i] <= 32:
i += 1
val = 0
while i < nbytes and 48 <= data[i] <= 57:
val = val10 + (data[i] - 48)
i += 1
if not found:
cur += val
window.append(val)
while cur > X:
cur -= window.popleft()
if cur == X:
found = True
out.append("YES" if found else "NO")
sys.stdout.write("\n".join(out))
This avoids function call overhead. However it repeats parsing code for each integer. That's okay but a bit verbose. We could define a small inline function using def nxt(): but then call overhead. But we can use local variable for speed: In PyPy, function calls have some overhead but may be acceptable. For 10 million calls, overhead could be significant. So I'd prefer to inline. However to keep code clean, we could define a generator using yield? That also has overhead.
Given the high input size, I'll implement inlined parsing.
But careful: The code above uses separate while loops for each integer. It also correctly skips whitespace before each integer. However we must ensure that after reading the last integer of a test case, the next iteration for the next test case will correctly skip any whitespace before N. That's handled because before parsing N we have a while loop skipping whitespace. So good.
Now, we need to parse t similarly. Already done.
Now, consider that the input might have trailing newline after last number. The while loops will skip it at the beginning of next parse, but since no next parse, fine.
Now, test with sample.
But there is a potential issue: In the loop for N costs, we use for _ in range(N): and inside we parse a cost. But what if N=0? Constraint says N >= 1, so fine.
Now, we need to think about memory: window deque may hold many elements. The deque's popleft is O(1). Good.
Now, we should also consider that if found becomes True early, we still parse all remaining costs. That's necessary to advance i. Could we skip parsing? We could compute that there are remaining numbers and advance i by scanning for newlines? That would be complicated; just parsing them is simpler and ensures we read them; overhead is minimal if we are just parsing digits and discarding. We still have to iterate over the characters anyway, so we can't skip. So it's fine.
Now, we should ensure that the while loops for parsing each integer correctly handle the case where there is no integer (but N ensures there is). So fine.
Now, we need to think about the possibility of integer overflow in the intermediate accumulation? Python unlimited.
Now, we need to produce final answer.
But there is a catch: The problem statement says: "Next N line contains N integers, where i^th line contains i^th integer". That could also be interpreted that each line contains N integers? Actually the phrasing is ambiguous: "Next N line contains N integers, where i^th line contains i^th integer, which represents the Costi." Could also mean that there are N lines, each containing one integer. That's what we used. However sometimes they might write "Next line contains N integers" meaning a single line with all costs. But they explicitly say "Next N line contains N integers, where i^th line contains i^th integer". That indicates each on separate line. Our parser works for both, because it just reads ints irrespective of line boundaries. So it's fine.
Now, test with a case where all costs are on one line: e.g., "1 2 3" on one line. Our parser would still read three ints. So it's robust.
Now, let's consider time: The code has loops for each integer that also skip whitespace. For each integer, we have a while loop skipping whitespace (usually one char per number, the newline). Then we have a while loop reading digits. So total character operations per integer: about (digit count + 1). So overall similar to earlier.
Now, we need to ensure we don't inadvertently skip non-whitespace characters that might be part of numbers? We only skip characters with code <= 32. Digits are >32. So fine. Other characters like '-' could appear? Not in constraints.
Now, we must ensure that we correctly handle the case where after reading a number, we land on a character that is >32 but not a digit (like '.'), but input will not have such. So fine.
Now, final code.
But we need to be careful: In the loop for each test case, we parse N and X. Then we loop for N costs. At the end of the test case, i should be positioned at the start of the next test case's first integer (or EOF). That's fine.
Now, we should also consider the case where T might be 0? Constraints T>=1.
Now, what about reading t: we parse t. But if there are blank lines before t? The problem probably starts directly. We skip whitespace anyway, so fine.
Now, we should test on a few scenarios.
Test 1: Input:
1
5 12
1
3
4
5
2
Our code: i starts at 0, skip whitespace? The first char is '1' (code 49), not <=32, so read t=1. Then i after reading '1' is at newline? Actually after reading t, we exited the digit loop and are at the character after the last digit. That character is newline (\n). Next, for test case loop: first parse N: while skip whitespace (newline) -> i increments past newline, then encounter '5', read N=5. Then skip whitespace, read X=12. Then loop for costs: For each of 5, parse val: skip whitespace (newline), read digit(s) etc. Works.
Test 2: Input with multiple test cases and extra newline:
2
3 3
1
1
1
2 5
2
2
Our code should handle.
Now, test with large values: Not necessary.
Now, potential bug: In the for loop for costs, we used for _ in range(N): and inside we parse the cost. But what if there are fewer numbers available due to malformed input? Not our concern.
Now, one more nuance: The sliding window algorithm using deque: when cur > X, we pop left until cur <= X. But we must ensure that we don't pop when window is empty. But if cur > X and window empty, cur must be 0, impossible. So fine.
Now, we need to confirm that the algorithm works for X up to 1e12 and cur up to sum of all costs, which could be up to 1e12. Python int fine.
Now, is there any scenario where the window might become empty and cur still > X? If X is negative? Not allowed. So safe.
Now, final code.
But to be thorough, we should also think about the possibility that the input has multiple spaces between numbers. Our skip while data[i] <= 32 will skip spaces and tabs. Good.
Now, edge case: If a number is 0? Constraint says Costi >= 1, so positive. So while condition while cur > X will shrink; but if Costi are all positive, sum strictly increases with r. But note: The problem says 1 ≤ Costi ≤ 10^6, so positive.
Thus algorithm is correct.
Now, we must ensure that the output is exactly "YES" or "NO" in uppercase per sample.
Now, we write final answer.
Given the complexity, we can produce a single function solve with inlined parsing.
But we also need to consider that the input might be huge and the code might be too slow if we use Python's default CPython. The contest might allow PyPy, which is faster for loops. I'll mention in solution to use PyPy for better performance. But we just need to provide code.
Now, I'll produce the final code.
Before final, let's think about potential improvements: We could avoid deque by using a simple list and index pointers: store all costs in a list (which we need to read anyway) and maintain left pointer. But we already argued that reading costs into a list and then processing in a second loop might be slower due to two passes? However, we could process as we read: we read a cost, append to a list, then use left pointer to index into the list. But to pop from left, we can't efficiently remove from list; we would just increment left pointer and not delete the elements. That's fine: we can store all costs in a list, and maintain left index. The list will hold all N elements. The left pointer is just an integer. When we need to subtract from cur, we subtract arr[left] and increment left. That's O(1) per pop. That avoids deque overhead and might be faster because list indexing is very fast. However we still store all elements. But in the case where we break early, we might not need all, but we still read them all? Actually if we break early, we still need to read the remaining costs (to consume input), but we could skip adding them to the list? But if we break early, we could just continue reading without storing them. However we can design: while reading, if not found, we append to list and process; if found, we just parse and discard (not storing). That way we don't store unnecessary costs after found. That's similar to deque but with list; if found early, list size is limited to the number read before found. If not found, list size = N. So it's similar.
But using list with left pointer: we need to know the value at left when we subtract. If we don't pop from list, we just have left index. The list stores all read elements (until found). For subtraction, we do cur -= arr[left]; left += 1. That works. However we also need to know the current window's elements? Not really. So we can avoid deque and use list + left pointer.
But careful: If we break early and then discard remaining numbers, the list is only up to found index. That's fine.
If not found, we store all N in list. That's same as deque but list might be more memory efficient because it stores references in contiguous array, while deque uses blocks. However list of Python ints still stores pointers to int objects; int objects themselves are separate. But both store int objects. So memory similar.
Performance wise, list appending and indexing is very fast. Deque's popleft is also O(1) but may involve more overhead. So I think using list and left pointer is slightly faster and simpler.
Let's implement that:
For each test case:
arr = [] # to store costs (only while not found)
left = 0
cur = 0
found = False
for i in range(N):
val = next_int()
if not found:
cur += val
arr.append(val)
while cur > X:
cur -= arr[left]
left += 1
if cur == X:
found = True
# else: discard
But note: When we shrink, we need to subtract arr[left] which is the leftmost element still in window. However we never remove elements from arr, we just move left pointer. That's fine. The arr may contain elements before left that are no longer in window; they are just extra. That's okay. The arr will grow up to N if not found. In case found early, arr size is up to r+1 (the point of found). That's fine. Memory: worst-case arr size N. That's similar to deque. But with deque, we actually remove elements from front, freeing memory (the deque blocks may be freed). With list, the arr holds all elements even after left moves, so memory remains O(N) even if the window size is small? Actually if we never find and we process all N, the window may shrink and left may move, but arr still holds all N elements because we appended all. So arr size = N. That's fine. But if we found early, we stop storing new elements, but arr still holds all read elements up to found. That could be up to N as well if found at the end. So it's fine.
But what about the case where we process all N and window size could be small at the end (like left near N-1), but arr still holds all N. That's okay. The memory is N ints regardless.
Thus using list is simpler and might be faster due to less overhead of deque.
But there is a subtlety: With list, when we do while cur > X: cur -= arr[left]; left += 1; we must ensure left index doesn't exceed len(arr). Since cur > X implies window non-empty, left < len(arr). So okay.
Thus we can avoid importing deque.
Now, we need to be careful: If we break early (found), we don't need to store further values, but we still need to read them. So we can just parse them and not append.
Thus the code becomes:
found = False
window = [] # rename to window but it's a list
left = 0
cur = 0
for _ in range(N):
val = parse_int()
if not found:
cur += val
window.append(val)
while cur > X:
cur -= window[left]
left += 1
if cur == X:
found = True
# else: do nothing
Now, after found, we just parse remaining values.
Now, this uses list and left pointer.
But note: After we shrink, left pointer increases, but window list still holds earlier elements. That's fine.
Now, we need to be careful: If we break early and then later we read more numbers but we don't store them, that's fine.
Now, we need to parse ints. We'll inline parse.
Now, this reduces import of deque and may be slightly faster.
Let's test with example where we need to shrink multiple times:
Now, what about a case where window becomes empty? e.g., after popping all, left equals len(window). That's okay, cur becomes 0. Next iteration we add new val.
Now, all good.
Thus we can implement without deque.
Now, we also need to ensure that we don't run out of memory due to list holding many ints. It's fine.
Now, finalize code.
I'll write solve() function with inlined parsing.
But one more optimization: For parsing, we can pre-convert the bytes to a memoryview? Not needed.
Now, code:
import sys
def solve():
data = sys.stdin.buffer.read()
n = len(data)
idx = 0
code
# read T
while idx < n and data[idx] <= 32:
idx += 1
t = 0
while idx < n and 48 <= data[idx] <= 57:
t = t * 10 + (data[idx] - 48)
idx += 1
out_lines = []
for _ in range(t):
# read N
while idx < n and data[idx] <= 32:
idx += 1
N = 0
while idx < n and 48 <= data[idx] <= 57:
N = N * 10 + (data[idx] - 48)
idx += 1
# read X
while idx < n and data[idx] <= 32:
idx += 1
X = 0
while idx < n and 48 <= data[idx] <= 57:
X = X * 10 + (data[idx] - 48)
idx += 1
window = [] # list to store costs (only while not found)
left = 0
cur = 0
found = False
for i in range(N):
# read cost
while idx < n and data[idx] <= 32:
idx += 1
val = 0
while idx < n and 48 <= data[idx] <= 57:
val = val * 10 + (data[idx] - 48)
idx += 1
if not found:
cur += val
window.append(val)
while cur > X:
cur -= window[left]
left += 1
if cur == X:
found = True
# else skip processing
out_lines.append("YES" if found else "NO")
sys.stdout.write("\n".join(out_lines))
if name == "main":
solve()
Now, test with sample:
Input: "1\n5 12\n1\n3\n4\n5\n2\n"
Let's simulate quickly: t=1. Then N=5, X=12. Then loop i=0..4, parse values. At i=3, found becomes True. Then i=4 parse but skip. Output YES.
Works.
Now, we should test with a case where multiple test cases, and also where answer is NO.
We'll trust.
Now, potential off-by-one: After reading the last cost, idx might be at EOF or newline. For next test case, we skip whitespace before reading N, which will skip the newline after the last cost of previous test case. Then we parse N. Good.
Now, ensure that after reading t, we don't accidentally skip a newline that is part of the next number? Actually after reading t, we are at the character after the last digit of t, which is likely newline. Then in the for loop, before reading N, we skip whitespace, so we skip that newline, then start reading N. Good.
Now, consider case where there is no newline after last number? The last character might be digit. Then after reading the last cost, idx will be at EOF (n). Next iteration of test case loop (if more test cases) would try to skip whitespace; idx < n false, so while loop doesn't run. Then reading N would attempt while idx < n and data[idx] <= 32, but idx==n, so skip, then N=0 while? The while for digits would not execute because idx==n, so N stays 0. That would cause issues. But does input guarantee a newline at the end? Typically yes, but not guaranteed. However it's safe to assume there is a newline or at least whitespace after each line? The problem statement says "Next N line contains N integers", each on its own line. So each line ends with newline. So after the last cost, there is a newline. Also after the last test case, there may be a newline. So idx will end at a newline after reading the last cost. Then for the next test case (if exists), we skip whitespace including that newline, then read N. So good. For the last test case, after processing, we won't read further. So it's okay.
But if there is no trailing newline, the last number would be at end of file. After reading the last cost, idx will be at EOF. Then the test case ends. Since there is no next test case, we don't need to parse further. So it's fine. The for loop for test cases ends, we output. So no problem.
Now, ensure that after reading the last cost, the while loops for reading cost may end at EOF. That's okay.
Now, time complexity: The loops parse each character exactly once. The sliding window inner while loop may cause multiple subtractions but total across all r is O(N). So overall O(total input size + total N). Should be fast.
Now, consider that X may be very large (1e12) and cur may become large, but Python int operations are fine.
Now, I think the solution is ready.
We should also consider an alternative: Use prefix sum and hash set? Since numbers are positive, sliding window is optimal O(N). Prefix sum + hash set would be O(N) but requires O(N) memory for set. That could also work, but sliding window is simpler with positive numbers.
Now, final answer: Provide code with explanation.
But the problem statement might have a nuance: "friends which are in continuous range" meaning contiguous. So our approach is correct.
Now, we can produce the final answer.
I'll write final solution with comments to explain.
Given the output should be exactly T lines.
Now, final answer in "final" channel. ```python
import sys
def solve() -> None:
# read the entire input as bytes
data = sys.stdin.buffer.read()
nbytes = len(data)
idx = 0
code
# ----- read number of test cases (T) -----
while idx < nbytes and data[idx] <= 32: # skip whitespace
idx += 1
t = 0
while idx < nbytes and 48 <= data[idx] <= 57:
t = t * 10 + (data[idx] - 48)
idx += 1
out = []
for _ in range(t):
# ----- read N and X -----
while idx < nbytes and data[idx] <= 32:
idx += 1
N = 0
while idx < nbytes and 48 <= data[idx] <= 57:
N = N * 10 + (data[idx] - 48)
idx += 1
while idx < nbytes and data[idx] <= 32:
idx += 1
X = 0
while idx < nbytes and 48 <= data[idx] <= 57:
X = X * 10 + (data[idx] - 48)
idx += 1
# ----- sliding window on the costs -----
window = [] # stores the costs seen so far (only while answer not found)
left = 0 # index of the current window's left end inside `window`
cur_sum = 0
found = False
for _ in range(N):
# read next cost
while idx < nbytes and data[idx] <= 32:
idx += 1
val = 0
while idx < nbytes and 48 <= data[idx] <= 57:
val = val * 10 + (data[idx] - 48)
idx += 1
if not found:
cur_sum += val
window.append(val)
# shrink window from the left while sum exceeds X
while cur_sum > X:
cur_sum -= window[left]
left += 1
if cur_sum == X:
found = True
# else: already found the answer – just consume the remaining numbers
out.append("YES" if found else "NO")
sys.stdout.write("\n".join(out))