We need to solve the problem: given N integers (beverage sizes), determine if any three distinct elements sum to X. Constraints: N >= 3, values <= 30000, but N may be up to? Not specified, but given typical constraints maybe up to 10^5 or more. We need efficient solution.
The problem statement: "If quantity of any three drinks add up to X then we'll have it else we'll return the order. E.g. If a + d + f = X then True else False." They talk about "different drinks" and order for a random number of different drinks. The input gives N bottles, sizes. Probably assume distinct? Not necessarily; they say "different drinks" but they could be different types, so sizes may be same? Usually the problem is classic 3-sum. We'll treat as standard: find any triple (i, j, k) such that a_i + a_j + a_k = X. The indices are distinct.
We need output "True" if possible else "False".
Sample: N=6, sizes = [1,4,45,6,10,8], X=22 -> 4+10+8=22 -> True.
We can solve with sorting + two-pointer technique O(N^2). Since N may be large? Constraint not given exactly, but values up to 30000. Could be up to maybe 2000? But typical 3-sum problem with N up to 3000 works O(N^2). But there is also constraint "X,a ≤ 30000", meaning values moderate. But N could be large. We could also use hash set approach: for each i, for each j, check if X - a_i - a_j is in set (but careful about distinct indices). That would be O(N^2) as well, but could be faster with small values? But O(N^2) may be too slow for N ~10^5.
Given that values are bounded (<= 30000), we could use counting (frequencies) and then iterate possible values. Since X <= 30000, a_i <= 30000. Then we can treat as multi-set. To check if there exist three numbers (allowing repeats if there are duplicates) that sum to X. But we need distinct drinks? The problem says "different drinks" but they could be of same size but still different drinks? Usually in 3-sum, indices distinct but values can be equal. The phrase "different drinks" might refer to different types, but sizes can be same? Probably not important; we consider distinct indices, not distinct values.
If we have counts, we need to ensure that we have enough copies to form triple. That's doable. Complexity: O(max_val^2) perhaps? Max val = 30000, so iterating over all pairs up to 30000*30000 = 9e8, too large.
Better to stick with O(N^2) two-pointer, but N may be up to 2000? Or maybe they expect O(N^2) with N up to 2000. But we need to parse input: first line N, next line "size of bottles present in string format." That likely means numbers separated by spaces. We'll read them.
Given that constraints: N ≥ 3, X,a ≤ 30000. So maybe N can be up to 10^4 or 10^5? O(N^2) might be borderline.
Alternatively we can use two-pointer after sorting: for i from 0 to N-2, use left = i+1, right = N-1 to find if two sum to X - a[i]. This is O(N^2) worst-case but average maybe okay. With N=10^5, O(N^2) is too slow. But maybe N is small. Let's check typical coding problems: 3-sum problem often N <= 3000. Also given values are <=30000, maybe they want a solution using frequency array? But that would be O( max_value^2 ) = 9e8, which is too high.
Maybe we can use hash set for two-sum for each i, but careful about using same element twice. For each i, we can insert all numbers after i? Actually we can do: for i from 0 to N-2, for j from i+1 to N-1, check if X - a[i] - a[j] exists in a hash set of the remaining numbers. But we can maintain a set of numbers from j+1 to N-1? That would still be O(N^3). Or we can do: sort, then two-pointer as described, that's O(N^2). With N up to 2000, O(4 million) fine; up to 5000 O(25 million) fine; up to 10000 O(100 million) may be borderline but okay in C++ but in Python maybe too slow. In Python, O(N^2) for N=10000 is 100 million operations, which is too high. For N=2000 it's 4 million, fine.
Maybe constraints are such that N <= 2000. But not provided.
Let's search memory: The problem statement looks like from some platform (maybe HackerEarth). Many HackerEarth problems have N up to 10^5, but then 3-sum can't be done naively. However, there is a technique using FFT? Or perhaps they ask to output True/False, not indices. Could be done using boolean array of size X+1? Actually, we could do: for each a, we can generate possible sums of two numbers, then check if any a_i + two_sum? Wait.
Alternative: Since X and a_i are limited to 30000, we can use bitset convolution. We could represent the set of numbers as a bitset of size (max_val+1). Then compute the convolution (via bitset shift and AND) to check for triple sum? Actually, to test if there exists i, j, k such that a_i + a_j + a_k = X. We can use generating function: Let A be a boolean vector where A[v] = 1 if v appears (with multiplicity? But need distinct indices). If we allow using same element multiple times? We need distinct drinks, but if there are enough copies, it's allowed. The problem says "different drinks" meaning distinct drinks, so we cannot use same drink twice. But if there are duplicate sizes, we can use different drinks of same size. So we need to ensure multiplicity. So we need to handle counts.
But we could use a frequency array freq of size up to 30001. Then we need to check if there exist three numbers (i, j, k) possibly with repeats such that i, j, k are within the multiset with sufficient counts. This can be solved by iterating over possible values and checking conditions. Since max value is only 30000, we could do O(max_val^2) but that's 9e8, too high. However we can optimize: Use two loops over possible values but with pruning and using freq. Actually typical solution: For i from 0 to X: if freq[i] > 0, then for j from i to X - i: if freq[j] > 0, then k = X - i - j, if k >= j and freq[k] > 0, then check if we have enough counts (considering cases of equality). This triple loop over value ranges, but we can limit j from i to X-i. But worst-case X=30000, so number of pairs (i, j) is about (X^2)/2 ~ 450 million, still large. But we can break early? Not likely.
Better to use sort and two-pointer on the distinct values list? But if there are many duplicates, we can compress with frequencies and then use algorithm on distinct values (M distinct). M could be up to 30001, which is manageable. Then we can treat each distinct value as a candidate and use two-pointer on distinct values. But we need to handle multiplicities: to form a triple, we need to ensure that we have enough copies. So we can iterate over distinct values list (sorted). For each i as index of distinct values, for each j from i to end, use two-pointer? Actually typical 3-sum on distinct values with counts. We can do: for each distinct value a (index i), we need to find two other values b and c (distinct indices or possibly same) such that b + c = X - a. We can perform two-pointer on the distinct values array (size M). For each i, we set l = i (or i? careful about using same element) and r = M-1, but we need to handle counts. Complexity O(M^2) worst-case if we do for each i, two-pointer scan from i to M-1? Actually standard two-pointer for 3-sum on sorted array of N elements is O(N^2) because for each i we run l and r that move inward total O(N) per i? Wait, typical algorithm: for i from 0 to N-3, set l = i+1, r = N-1, then while l < r: check sum. For each i, l and r move from extremes to center, overall O(N) for each i? Actually total operations over all i is O(N^2) because for each i, l and r can move O(N) steps? But careful: In the standard 3-sum, the total number of operations is O(N^2) because for each i, l starts at i+1 and r at N-1, and they move inward; across all i, each movement of l or r is at most O(N) times? Let's think: The total number of (l, r) pairs considered across all i is O(N^2). Actually the algorithm is O(N^2) because each i, we might traverse many positions. However there is a more efficient two-pointer? Actually typical 3-sum code: for i in range(n-2): l = i+1, r = n-1; while l < r: sum = a[i]+a[l]+a[r]; if sum == target: found; else if sum < target: l++; else r--. This is O(N^2) because for each i, while loop runs at most O(N) times, giving O(N^2). So it's quadratic.
If we compress to distinct values M, the algorithm would be O(M^2) which could be up to 30000^2 = 9e8, too high. So that doesn't help.
But maybe N is not that large; the values bound is 30000, but N could be, say, 1000. So O(N^2) is fine.
Given it's a typical coding challenge, they likely expect a O(N^2) solution after sorting.
But the problem statement: "N ≥ 3, X,a ≤ 30000". That's all. So they didn't give upper bound for N. In such cases, I'd assume N can be up to maybe 10^5? But then O(N^2) is impossible. However there are known algorithms for 3-sum in sub-quadratic time? It's generally believed 3-sum requires Ω(n^2) in the worst-case in the algebraic decision tree model. But that's for arbitrary numbers. For numbers bounded by constant, we can do faster using FFT or bitset. Since a_i ≤ 30000, we can use convolution to compute the number of ways to get sums of two numbers, then check with third. However, we need to consider distinct indices and multiplicities. We can use generating functions with counts and then subtract overcounts when using same index multiple times. But there is a known approach: Use an array freq[0..30000]. Then compute the convolution of freq with itself (using FFT) to get freq2[sum] = number of ordered pairs (i, j) (with i and j possibly same) that sum to that value. But we need unordered pairs? Actually we need number of ways to pick two distinct indices (allowing same value if there are enough copies). Then for each third value k, we check if freq2[X - k] > (something) to ensure at least one pair not using the k index. That can be handled by subtracting contributions where the pair includes k. This becomes messy but doable.
But maybe simpler: since constraints are small (values <= 30000), we can use a boolean bitset approach. For each number, we can maintain a bitset representing which sums of two numbers are achievable. But we need to avoid using same element twice. One classic approach for 3-sum with small numbers: Use a boolean array possibleSum2 of size X+1 (since we only care sums up to X). Then for each i, we can check if possibleSum2[X - a[i]] is true, where possibleSum2[s] indicates if there exist two earlier (or later) indices that sum to s without using i. This is similar to two-sum as we iterate: we maintain a set of seen numbers. For each i, we want to know if there exist j and k such that a[j] + a[k] = X - a[i] with j,k distinct and both not i. If we process i from 0 to N-1, and maintain a set of numbers we have seen so far (like for two-sum), we can for each i, after updating something? Actually we can do: For each i, we could check for each j < i if (X - a[i] - a[j]) is in set of numbers seen before j? That would be O(N^2). Not better.
We could try to precompute all pairwise sums and store them in a hash map mapping sum to list of index pairs. Then for each element, look up X - a[i] in the map and see if there exists a pair not containing i. That would be O(N^2) for building map (number of pairs). And space O(N^2) could be huge.
Thus likely N is moderate.
I'll check the problem source: It might be from "HackerEarth > Basic Programming > Input/Output > Basics of Input/Output". Possibly they expect an O(N^3) solution? No, that would be too slow. The sample is small. They might accept O(N^3) for N <= 100? But they gave constraint a <= 30000, not N. Could be N <= 100. But they didn't specify. Many HackerEarth easy problems have N up to 100.
Given it's a simple problem, I'll implement an O(N^2) solution after sorting. That should be fine for N up to a few thousand. If N is larger, time may exceed, but given the typical environment, they likely expect a quadratic solution.
Alternatively, we can use hash set approach with optimization: For i from 0 to N-2: create a hash set of numbers from i+1 to N-1? Actually we can do: for i in range(N):
needed = X - a[i]
# check if there exist two distinct numbers among the rest that sum to needed.
# This is classic two-sum on subarray i+1..N-1 if we sort and use two-pointer, or use hash set: iterate j from i+1 to N-1 and check if needed - a[j] in set of numbers seen after j? Actually we can use: For each i, we maintain a hash set of numbers from i+1 to N-1? That would be O(N^2) again.
We could try to precompute for each sum the indices pairs and store in a map, but that's O(N^2) building.
Thus I'll go with sorting and two-pointer.
Algorithm:
- Read N (int).
- Read list of N integers (maybe split string).
- Read X (int).
- Sort the list.
- For i in range(N-2):
left = i+1
right = N-1
target = X - arr[i]
while left < right:
cur = arr[left] + arr[right]
if cur == target:
print("True") and exit.
elif cur < target:
left += 1
else:
right -= 1
- If loop ends, print("False").
Need to handle duplicates: This algorithm will find a triple with distinct indices automatically.
Edge Cases: If there are multiple copies of same value, it's okay as long as indices are distinct. The algorithm may pick left and right such that they equal i? No, left starts at i+1, right at N-1, so distinct.
Complexity: O(N^2) time, O(1) extra space besides sorting.
Given that constraints include a_i <= 30000, sorting O(N log N) is fine.
Now, implement in Python.
Input format: first line N, second line contains the sizes as string (space-separated), third line X. Possibly there are extra spaces or newlines. We'll use input().strip().
Output exactly "True" or "False" with capital T/F.
Now, check sample:
N=6, arr=[1,4,45,6,10,8], X=22.
Sorted = [1,4,6,8,10,45].
i=0 (1): target=21, left=1 (4), right=5 (45): 4+45=49 >21, right=4 (10): 4+10=14 <21, left=2 (6): 6+10=16 <21, left=3 (8): 8+10=18 <21, left=4 (10): now left=4, right=4? Actually left=4, right=4, loop ends because left < right? condition left<right false, break.
i=1 (4): target=18, left=2 (6), right=5 (45): 6+45=51>18, right=4 (10): 6+10=16<18, left=3 (8): 8+10=18 == target => True. So output True.
Works.
Potential improvements: If N is large, we can break early if arr[i] > X and all positive? But values could be negative? Not stated; sizes are quantities, so likely non-negative (since they are sizes of bottles). But they said "a ≤ 30000" and presumably a >= 0 (size positive). So all non-negative. So we could break when arr[i] > X because then sum of three non-negative numbers would exceed X? But if numbers can be zero? a can be zero? Possibly? It says size of bottles, likely positive. So we can break if arr[i] > X because then even adding two zeros would be > X if others non-negative. However we cannot assume zeros exist. But since all numbers non-negative, if arr[i] > X, then arr[i] + any two non-negative > X, so no triple with that i works. So we can break out of loop when arr[i] > X. But careful: if numbers can be zero, arr[i] > X still too big. So break.
Also, we can skip duplicate i values to avoid redundant work: if arr[i] == arr[i-1], we can continue? But we need to consider triples that might use duplicate values; skipping may miss triples like [arr[i], arr[i], something] if we have at least two copies of the same value. For example, arr = [2,2,3], X=7 -> 2+2+3=7. If we skip duplicate i for i=1 because arr[1]==arr[0], we would skip and not check (i=1) and may not find triple because when i=0, we might find? With i=0 (2), target=5, left=1 (2), right=2 (3): 2+3=5 -> works. So it finds without duplicate i. So skipping duplicates for i is safe? Not always: Suppose arr = [1,1,1] X=3. i=0 target=2, left=1 right=2: 1+1=2 works. So it's fine. If we skip i=1 because duplicate, it's okay. However consider scenario where triple uses two of the same value but the third is also that value? That's three of same. For arr = [2,2,2] X=6, i=0 target=4, left=1 right=2: 2+2=4 works. So fine. So we can skip duplicate i after sorting to avoid extra loops, but not necessary. Skipping can reduce work if many duplicates. But we must ensure that we don't skip needed i when there might be a triple where the smallest element is duplicated and we need to consider that i? Actually the algorithm uses i as the first element. If there are duplicates, the first occurrence of that value will be considered, and it will pair with later indices that may include the same value. So all triples will be found because the smallest index of a given value will be considered, and that can pair with later same values. So it's safe to skip if arr[i] == arr[i-1] and we are only using i as first element. However, there is a nuance: if the triple consists of values a, b, c where a < b < c (sorted), then i will be index of a. If there are duplicate values for a, the smallest index among those a values will be used. So skipping later duplicates of a is fine. So we can add: if i>0 and arr[i] == arr[i-1]: continue. This is optional but improves.
But be careful: if numbers can be negative, then duplicates may affect? But not applicable.
Given all non-negative, we can also break if arr[i] > X.
Now implement:
def main():
import sys
data = sys.stdin.read().strip().split()
if not data: return
N = int(data[0])
arr = list(map(int, data[1:1+N]))
X = int(data[1+N])
arr.sort()
for i in range(N-2):
if i>0 and arr[i]==arr[i-1]:
continue
if arr[i] > X: # since sorted and non-negative
break
target = X - arr[i]
left, right = i+1, N-1
while left < right:
cur = arr[left] + arr[right]
if cur == target:
print("True")
return
elif cur < target:
left += 1
else:
right -= 1
print("False")
This should work.
But is it guaranteed that all numbers are non-negative? The constraints say a ≤ 30000, but it does not specify lower bound. Typically sizes are positive, but could be zero? If zero allowed, arr[i] > X break may be too early because later zeros maybe still produce sum? Actually if arr[i] > X, then arr[i] + any two non-negative numbers (≥0) would be > X, so break is fine. If there are negative numbers, then arr[i] > X does not guarantee that because later numbers could be negative to bring sum down. But constraints say a ≤ 30000, could be negative? Usually they would say 0 ≤ a ≤ 30000 if non-negative. The notation "a ≤ 30000" just gives an upper bound; negative numbers would be less than 30000, but they didn't give lower bound. In many problems, they imply non-negative but not always. To be safe, we can omit the break, or keep it with a note that it's okay for non-negative. But I'm not sure. Since it's bottle sizes, it's likely positive. However, for completeness, we can keep the break condition but only if we assume non-negative. But if negative allowed, the sorting order would have negatives first, so breaking when arr[i] > X would also be valid? Suppose X is positive, and arr[i] > X, but later there are negative numbers? Actually after sorting, if arr[i] > X, then all subsequent arr[j] >= arr[i] > X, so all numbers are > X. Sum of three numbers > X would be > X (since all > X, sum > 3X > X). So even with negative numbers, if the smallest number after sorting is > X, then all numbers are > X. But if there are negative numbers, they would appear before positive numbers, so the sorted array would have negatives first, then positives. So if we encounter an element > X, that means from that point onward, all elements are > X. However, we might have missed triples that involve earlier negative numbers and later > X numbers? But earlier i indices (with negative numbers) have already been considered. Once we reach i where arr[i] > X, those indices are later in the array, but there could still be triples involving two negative numbers and one > X? Wait, we are iterating i from start to N-2. When i reaches an index where arr[i] > X, that means this element and all later elements are > X. But could there be triples with i as first element and later two elements? Since later elements are > X, arr[i] > X, so sum > X (since sum of three > X numbers > X). So no triple with i as first element works. Could there be triples with earlier i (which we already processed) and later j, k? That would have been considered when i was earlier. So we can break safely. If arr[i] is exactly > X, but earlier there may be negative numbers that combine? But those would have been processed when i was those negative numbers. So we can break.
But careful: if numbers can be negative, it's possible that arr[i] > X but later numbers are also > X, but sum of a negative (i) and two large numbers might equal X? But i is the first element, so if we are at i where arr[i] > X, that means all previous i values are less than or equal to arr[i] (since sorted). But previous i values could be negative, but we have already processed them. So no need to process current i onward. So break is safe.
But is there a case where arr[i] > X but there exists j and k such that arr[j] and arr[k] are negative? But j and k would be after i? Since sorted, negative numbers come before positives. If arr[i] > X, then any j > i will have arr[j] >= arr[i] > X, thus not negative. So j and k cannot be negative. So sum of positive numbers would exceed X. So break safe.
Thus break condition is valid for all integer arrays when sorted: if arr[i] > X, then any triple with arr[i] as smallest (or any element) will have sum > X? Actually if arr[i] is not necessarily the smallest; when we iterate i in increasing order, arr[i] is increasing. So when we encounter an arr[i] > X, for any triple where the smallest index is i (i is the smallest index of the triple, not necessarily the smallest value? But after sorting, indices correspond to sorted order. In our algorithm, i is the first index (lowest value). For a triple (i<j<k), the smallest value is arr[i]. So if arr[i] > X, then sum = arr[i] + arr[j] + arr[k] > X (since arr[j], arr[k] >= arr[i] > X, so sum > 3*X? Actually if X is positive, but X could be less than arr[i]. But what if X is negative? X ≤ 30000 but could be negative? It says X,a ≤ 30000, again only upper bound. If X is negative, it's possible arr[i] > X but arr[i] could be -10 and X = -20? Wait, if X is negative, arr[i] > X could be true for many numbers; but break when arr[i] > X could be too early because maybe we still need to consider larger numbers that sum to negative X? Example: arr = [-100, -50, 70], X = -80? Actually X negative, but X <= 30000, so could be negative. Then sorted: [-100, -50, 70]. For i=0, arr[i] = -100, target = X - (-100) = (-80) +100 = 20. left=1 (-50), right=2 (70): -50+70=20 => works. That's fine. For i=1: arr[1] = -50, target = -30? Actually X - (-50) = -80+50 = -30. left=2 (70): need two numbers sum to -30 but only one left, so none. i=2 not considered. If we break when arr[i] > X: X = -80, arr[0] = -100 is not > -80 (since -100 < -80), so we continue. At i=1, arr[1] = -50 is > -80? -50 > -80, so break. That would skip i=1, which is fine because i=1 cannot be the smallest in a valid triple? But could there be a triple with smallest index i=1? That would require j and k >1, i.e., (1,2,?) only two indices left? Actually with i=1, we need two other indices >1, which exist (2). So we would check i=1 and find no triple. Breaking at i=1 would skip that check but that's okay because we already found the triple at i=0. But what if the triple's smallest index is i=1 and we break before checking it? That could cause missing a triple if the triple exists with smallest index i=1 and we didn't find it at i=0. For example, consider arr = [-50, -30, 80], X = 0. Triple: -50 + -30 + 80 = 0. Sorted: [-50, -30, 80]. i=0: target = 0 - (-50) = 50, left=1 (-30), right=2 (80): -30+80=50 -> works. So found. Good.
Consider a triple where the smallest index is i=1 but i=0 is not part of any triple. Could that happen? Since arr is sorted, the smallest value among the triple is at the smallest index. If the smallest index of the triple is i=1, that means arr[0] is not in the triple. But could there be a triple with indices (1,2,3) that sums to X, and arr[0] is less than arr[1]? Yes. In that case, when i=0, we would not find a triple because we would be considering i=0 and looking for pairs among later indices to sum to X - arr[0]. That may or may not succeed. If it fails, we would then go to i=1 and possibly find the triple. If we break at i=1 because arr[1] > X, we might miss it. So we need to check: If arr[1] > X, could a triple with smallest index 1 sum to X? Since arr[1] is the smallest of the triple, the sum would be at least 3 * arr[1] if all positive? But if numbers can be negative, arr[1] > X does not guarantee sum > X. For example, X = 10, arr[1] = 20, but arr[2] and arr[3] could be negative large enough to bring sum down to 10? But because arr is sorted, if arr[1] = 20, then arr[2] >= 20 and arr[3] >= 20 (since sorted ascending). Actually sorted: arr[0] <= arr[1] <= arr[2] <= arr[3]... If arr[1] = 20, then arr[2] >= 20, arr[3] >= 20. Sum of three numbers each >=20 is at least 60, which is >10. So sum cannot be 10. So break is safe if we assume numbers are integers and sorted. In general, if the smallest element of the triple is s = arr[i], then the other two are >= s, so sum >= 3s. If s > X, then 3s > X if X is positive? But what if X is negative and s > X? For example, X = -10, s = -5 (since -5 > -10). Then 3s = -15, which is less than -10. So sum could be > X? Wait sum >= 3s = -15. Could sum be -10? Possibly if the other two are larger than s, sum would be > -15. For example, s=-5, then we could have -5 + -5 + 0 = -10. That sum is -10, equal to X. Here s = -5 > X (-10) is true (since -5 > -10). So if we break when arr[i] > X, and X is negative, then we might break at i where arr[i] = -5, but there could be a triple with smallest value -5 that sums to -10. But would arr[i] = -5 be > X? Yes. But we would break, missing that triple. But would that triple be found at a previous i? If arr[0] is less than -5, say -20, then i=0 would have been processed and might not have found triple? Possibly the triple uses i=1 as smallest. So break could be unsafe for negative X.
Thus, break condition arr[i] > X is only safe if we can guarantee that when arr[i] > X, the sum of three numbers with smallest = arr[i] cannot equal X. Is that always true? Let's analyze: For any triple (i < j < k) with values a_i <= a_j <= a_k. Sum = a_i + a_j + a_k. Since a_j >= a_i and a_k >= a_i, we have sum >= 3a_i. Also sum <= 3a_k, but that's not relevant. So sum >= 3a_i. For sum to equal X, we need 3a_i <= X, i.e., a_i <= X/3. So if a_i > X/3, then sum > X? Actually if a_i > X/3, then 3a_i > X, so sum > X (since sum >= 3a_i > X). So indeed, if a_i > X/3, then sum cannot equal X. That's a stronger condition. For non-negative numbers, X/3 may be smaller, but for negative numbers, X/3 might be bigger (since dividing negative flips inequalities). Let's check: If X is negative, say X = -10, then X/3 ≈ -3.33. If a_i = -5, then a_i > X/3? -5 > -3.33? No, -5 is less than -3.33. Actually -5 < -3.33. So a_i > X/3 is false. So condition a_i > X/3 is not satisfied. So break when a_i > X/3 would be safe: if a_i > X/3, then sum > X (since sum >= 3a_i > X). That holds for any real numbers because if a_i > X/3, then 3a_i > X, and sum >= 3*a_i > X, so sum cannot equal X. Conversely, if a_i <= X/3, it's possible. So we can break when a_i > X/3. But careful: if X is positive, X/3 positive; if X negative, X/3 negative; if X zero, break when a_i > 0. That seems safe. Also if there are negative numbers, a_i could be less than X/3 but sum could still be X? Yes. So we can break at first a_i > X/3. Since array sorted, once a_i > X/3, all later a_j >= a_i > X/3, so no triple can sum to X. So we can break.
Thus implement break condition: if arr[i] > X//3 (integer division) but careful: if X is not divisible by 3, we need to compare float? Actually condition is arr[i] > X/3. Since arr[i] is integer, we can check 3arr[i] > X. Because if 3arr[i] > X, then arr[i] > X/3. So we can break if 3arr[i] > X. That's a safe break regardless of sign? Let's test with negative: X = -10, arr[i] = -3: 3(-3) = -9 > -10? Yes, -9 > -10, so break? But if arr[i] = -3, then 3arr[i] = -9 > -10, so break would trigger. But can a triple with smallest element -3 sum to -10? Possibly: -3 + -3 + -4? But -4 is less than -3, so cannot be the smallest element; if smallest is -3, other elements must be >= -3, so the smallest sum possible with smallest -3 is -3 + -3 + -3 = -9. So indeed sum >= -9. But X = -10 is less than -9, so cannot equal -10. So break is correct: if 3arr[i] > X (i.e., sum lower bound exceeds X), then sum cannot be X because sum is at least 3arr[i] which is greater than X. Wait, we need sum == X; if lower bound > X, impossible. So condition is 3arr[i] > X. For X = -10, arr[i] = -3 gives lower bound -9 > -10, so no sum can be as low as -10, because the smallest sum is -9. So indeed no triple with smallest -3 can sum to -10. So break is correct.
If X = -10, arr[i] = -4: 3*(-4) = -12, which is less than -10, so lower bound -12 <= X, so could possibly sum to -10 (e.g., -4 + -4 + -2? But -2 > -4, so allowed? Actually -2 >= -4, so sum = -10 possible). So break not triggered. Good.
Thus break condition: if 3 * arr[i] > X: break.
But need to consider if numbers can be negative? It's safe. Also if numbers can be non-integer? They are integers. So we can use that.
But there's also possibility that arr[i] is large positive and X is also large, but 3*arr[i] > X would break. That can prune many loops.
We also need to consider that if X is negative and arr[i] is also negative but not too negative, break condition may not trigger early. That's fine.
Thus we can include: if 3 * arr[i] > X: break.
But is it always true that if 3 * arr[i] > X then no triple with i as smallest works? Yes, because for any j,k >= i, arr[j] >= arr[i] and arr[k] >= arr[i], so sum >= 3*arr[i] > X, so sum cannot equal X. So break.
Now, what about the case where arr[i] is very small (large negative) and X is also negative but large magnitude? 3arr[i] could be less than X (since both negative, e.g., arr[i] = -1000, X = -10 => 3arr[i] = -3000 < -10, so condition false, so continue). That's fine.
Thus we can incorporate break for efficiency.
But the problem constraints likely have X and a_i up to 30000, so non-negative, so either condition works.
Thus final algorithm with pruning.
Edge Cases:
We must output exactly "True" or "False" with capital first letter.
Now code.
I'll also consider alternative using set for two-sum for each i, but two-pointer after sorting is simpler.
Now, ensure we read input correctly. Use sys.stdin.read() to handle potential extra whitespace.
Potential Pitfalls:
-
Input may have multiple spaces or newline after second line. Using split works.
-
N may be larger than number of integers provided? But assume correct.
-
X may be on third line but after split we just take next token.
-
The list of sizes is on the next line, but could be split across multiple lines? Usually not.
Alright.
Let's write code.
Implementation:
import sys
def solve():
data = sys.stdin.read().strip().split()
if not data:
return
N = int(data[0])
arr = list(map(int, data[1:1+N]))
X = int(data[1+N])
arr.sort()
for i in range(N-2):
# optional skip duplicates
if i > 0 and arr[i] == arr[i-1]:
continue
if 3 * arr[i] > X:
break
target = X - arr[i]
left, right = i+1, N-1
while left < right:
cur = arr[left] + arr[right]
if cur == target:
print("True")
return
elif cur < target:
left += 1
else:
right -= 1
print("False")
if name == "main":
solve()
Now test with sample:
Input:
6
1 4 45 6 10 8
22
Output: True.
Test with no triple: N=3, 1 2 3, X=7 -> False.
Test with triple using duplicates: N=4, 2 2 3 1, X=7 -> after sort [1,2,2,3] -> i=0 (1) target=6, left=1 (2), right=3 (3): 2+3=5<6, left=2 (2): 2+3=5<6, left=3 => loop ends. i=1 (2) target=5, left=2 (2), right=3 (3): 2+3=5 => True. Works.
Test with all zero: N=3, 0 0 0, X=0 -> i=0 target=0, left=1 right=2: 0+0=0 -> True.
Test with negative numbers (if allowed): N=3, -1 0 1, X=0 -> sorted [-1,0,1]; i=0 target=1, left=1 right=2: 0+1=1 -> True. Works.
Now break condition: if 3arr[i] > X break. For X negative: N=3, arr = [-5, -4, -3], X = -12? Sorted: -5,-4,-3. i=0: 3(-5) = -15 > -12? -15 > -12 false, so continue. target = -12 - (-5) = -7, left=1(-4), right=2(-3): -4 + -3 = -7 -> True. Good. If X = -9, i=0: 3*(-5)=-15 > -9 false; target = -9 - (-5) = -4, left=1(-4), right=2(-3): -4 + -3 = -7 < -4? Actually -7 < -4, need larger sum? Since sorted ascending, two-pointer works with sum. At left=1(-4), right=2(-3): sum = -7 < -4, so left++? But left cannot exceed right. So no solution. i=1: 3*(-4) = -12 > -9 false; target = -9 - (-4) = -5, left=2(-3): only one element, loop not entered. So False. Good. If X = -8, i=0: target = -8 - (-5) = -3, left=1(-4), right=2(-3): -4 + -3 = -7 < -3, left++? left=2, right=2 exit. i=1: 3*(-4) = -12 > -8 false; target = -8 - (-4) = -4, left=2(-3): only one, none. So False. But is there a triple? -5 + -4 + -3 = -12. So not -8. Good.
Now test break: N=4, arr = [100, 101, 102, 103], X=10. Sorted same. i=0: 3*100=300 > 10 true -> break, loop ends -> False. Indeed no triple can sum to 10 because min sum 300. Good.
Thus solution seems correct.
Now, about time complexity: Worst-case when X is large such that no break, e.g., X = 90000, but a_i <= 30000, so 3arr[i] could be up to 90000, break only if arr[i] > X/3 => >30000, but arr[i] <=30000, so 3arr[i] <= 90000, break condition may not trigger until later. If X=90000 and arr values up to 30000, then for arr[i] <=30000, 3arr[i] <= 90000, so break condition never triggers (except maybe for >30000 but not possible). So we still do O(N^2). But N could be large, say 10^5, then O(N^2) impossible. But is that allowed given constraints a_i <= 30000? X could be up to 30000? Actually X <= 30000 per constraints. So X max is 30000. So if X <= 30000, then 3arr[i] > X can break for arr[i] > X/3. Since arr[i] <= 30000 but X <= 30000, X/3 <= 10000. So for arr[i] > 10000, break condition triggers. So if many elements > 10000, we break early. But if many elements are small (<=10000), then we may still have many i's. For example, X=30000, break when arr[i] > 10000, so we only consider i where arr[i] <= 10000. So if the array contains many small numbers, number of i we consider could be up to N, but those small numbers are at most 10001 distinct values? But N could be large, say N=10^5 all small numbers. Then we have to do O(N^2) on the portion of array where arr[i] <= 10000? Actually if all numbers are <=10000, then we never break and we iterate over all N-2 indices. For each i, we perform two-pointer that scans up to O(N) in worst-case. So total O(N^2) = 10^10, too much.
Thus we need to consider if N can be 10^5. If so, O(N^2) will not pass. But maybe constraints on N are lower. Since they didn't specify, but typical problems on HackerEarth (if this is from there) sometimes have N up to 10^5 and expect an O(N^2) solution? That would be unacceptable. But there are O(N^2) solutions that sometimes pass if constants are small? Not for 10^5.
Let's search memory: I recall a problem "Sheldon Cooper and Beverages" or something like that? It might be from some contest. I should maybe think about using a frequency-based method with O(max_val^2) but max_val is 30000, which is smaller than N possibly. Actually if N is huge (like 10^6), but values limited, we can compress. Then we can use two-pointer on distinct values M (<=30001). That would be O(M^2) = up to ~9e8, which is also high but could be borderline if optimized in C++ but not Python. However we can improve by using hash map and early exit? Actually 9e8 operations in Python is too much.
We need a more efficient algorithm given bounded values.
Another approach: Use a boolean array of size X+1 for single numbers? Since X <= 30000, we can use DP or generating function.
Idea: Since we need three numbers that sum to X, and each number <= 30000, X <= 30000. So we can use a technique: For each number a, we can mark its presence. Then we need to check if there exist three numbers (with distinct indices) that sum to X. Since values are bounded, we can use convolution via FFT to compute the number of ways to get sum of two numbers (with order). But then we need to ensure distinctness and avoid using same element multiple times. However because we have frequencies, we can adjust.
Simplify: Because X is at most 30000, we can simply iterate over all possible pairs (i, j) of values (distinct values with frequencies) and check if the third value exists, with careful handling of multiplicity. Since the number of distinct values M could be up to 30001, iterating over all pairs is O(M^2) which is about 9e8, which might be too slow in Python but could be optimized with early break? However 9e8 is definitely too slow. But perhaps M is not that large because values are limited to 30000, but if all numbers are distinct, M could be 30000. That's still high.
But we can reduce by only considering pairs where both values are within [0, X] because if a > X (and all numbers non-negative), then a cannot be part of triple? Actually if numbers can be zero, but if a > X, then even with two zeros sum > X. So for non-negative numbers, we can restrict to values <= X. Since X <= 30000, that's still up to 30001.
But we can also note that we are only interested in existence, not count. So we can use a boolean array twoSumPossible[0..X] indicating whether there exist two distinct numbers (with sufficient copies) that sum to that value. Then for each value a (or each number), we check if twoSumPossible[X - a] is true and that the triple doesn't reuse the same element more times than available. This can be done by building twoSumPossible in a way that accounts for frequencies and then verifying per element.
How to compute twoSumPossible efficiently? Since values are small, we can use a frequency array freq[0..X] (or up to max value). Then we can compute for each sum s whether there exist i and j (i <= j maybe) with enough copies. This is classic: For s, we need to check if there exist i and j such that i + j = s and (i != j and freq[i] >= 1, freq[j] >= 1) or (i == j and freq[i] >= 2). So we can loop over i from 0 to X, if freq[i] > 0, then for j from i to X - i, if freq[j] > 0, and (i != j or freq[i] >= 2), then twoSumPossible[i+j] = true. That's still O(X^2) ≈ 9e8. But maybe we can use bitset convolution? Since X <= 30000, we can represent freq as bitset (or boolean array) and then compute convolution via bitset shift-and operations. For each i, we shift the bitset by i and OR. But careful about multiplicities and distinctness. However we only need existence, not count. So we can have a bitset B where B[i]=1 if freq[i] > 0. Then the convolution (B shifted and ORed) gives possible sums of two numbers using distinct values but not caring about using same element twice if freq[i]>=2. But if freq[i]>=2, then i+i is possible if B has i, because shifting by i and AND with original B would give sum 2i? Actually using bitsets: we can compute twoSumPossible as the result of (B convolve B) > 0, but this convolution would count (i, j) with i and j possibly same. In bitset representation, we can compute using Python's integers as bitsets or use bitarray? Not needed. We can do: two_sum = bitarray(X+1) set to false. Then for i in range(X+1): if freq[i] > 0: two_sum = two_sum | (B << i) but then we also need to handle i = j? Actually if we do B shifted by i and OR, the resulting bitset will have 1 at positions s where there exists j such that B[j]=1 and i+j = s. But that's considering pairs (i, j) where i is the current loop value and j is any value with B[j]=1. This would include (i, j) with i fixed. If we OR over all i, we get all possible sums from two numbers. However this method uses shifting of entire bitset for each i, which is O(X * (X/wordsize))? If we implement B as Python's int used as bitset, shifting an int of up to X bits and OR-ing is O(size of int) which is O(X/wordsize) ~ O(X/30) maybe. Doing that for each i (X+1 times) gives O(X^2/wordsize) ~ (9e8/64) ~ 14 million operations, which might be acceptable in Python? Let's estimate: X=30000, bitset length 30001 bits => about 469 64-bit words (30001/64 ≈ 469). For each i where freq[i]>0, we shift B (which is 469 words) by i bits and OR into accumulator. The number of such i is M (distinct values <= X), up to 30001. So total operations ~ M * (X/wordsize) ≈ 30000 * 469 ≈ 14 million. That's not huge; 14 million integer operations in Python could be okay if implemented carefully using Python's big integers. However shifting a big integer by i bits and OR-ing is done in C, which is fast. So that might be feasible. Then after we have two_sum bitset indicating which sums are achievable with two numbers (distinct indices? Need to consider if using same element twice is allowed only if freq[i]>=2). The bitset method using B (presence of at least one) will also include sums like i+i if B[i]=1, because when we consider i in the loop and shift B by i, we get a bit at 2i because B[i] is 1, so that includes the pair (i, i) if we allow using same element twice. But that requires that we have at least two copies of i. If freq[i]==1, then we should not allow i+i as a sum. So we need to adjust for that. We can handle it by constructing two bitsets: one for at least one occurrence (B1) and one for at least two occurrences (B2). For sums with two distinct indices, we can compute using B1 but subtract the case where i=j and freq[i]<2. Alternatively, we can compute two_sum as: two_sum = (B1 convolution B1) but with the condition that for i=j, we need B2[i] (i.e., freq[i]>=2). But with bitset convolution using integer shifts, we can compute two_sum_excluding_same = (B1 shifted and ORed) but we must avoid adding i+i when freq[i]<2. We can handle by after computing a preliminary two_sum (including all), we can go over i where freq[i]==1 and set bit (2i could also be from j+k with j != k). So we need to check if 2*i is only possible from i+i. That's complicated.
Simpler: Since X <= 30000, we could just compute two_sum by nested loops but prune using that we only need to know existence, not all sums. We could compute on the fly when checking triples. Another approach: Use a frequency dictionary and then iterate over all distinct values a (with freq[a] > 0). For each a, we need to check if there exist b and c (with frequencies) such that b + c = X - a. We can iterate over b values (distinct) and compute c = X - a - b, check c in range and freq[c] sufficient. This is again O(M^2). But if M is 30000, that's 9e8, too high.
But perhaps N is not huge; the problem intends a simple solution.
Given that the constraints only mention a and X ≤ 30000, but not N, I'd assume N is also limited, maybe to 1000 or 5000, making O(N^2) acceptable. Many problems on platforms like HackerEarth have constraints: 1 ≤ N ≤ 5000, but they mention "a ≤ 30000". Since they didn't specify N upper bound, it's ambiguous.
We can search memory: I recall a problem "Sheldon Cooper and his beverage paradox" maybe? Actually there is a known problem "Sheldon Cooper and his beverage" on HackerRank? Not sure.
Given it's a sample with N=6, they likely expect a simple approach.
I'll adopt the O(N^2) solution.
But for completeness, I could also add a fallback using frequency for larger N? The problem might be from an automated judge that tests with moderate N.
I'll implement as described.
Edge Cases: If N is large but X small, break condition may cut early. So algorithm might be okay even for N up to 10^5 if many numbers are large? But if numbers are all small, we have O(N^2) which is bad. But if N=10^5 and all numbers <= 10000, then O(10^10) is too slow. So maybe testcases are designed to avoid that.
Given it's a problem about beverages, probably from a learning track, so N is small.
Thus I'll submit the O(N^2) solution.
One more thought: Could we use Python's itertools.combinations? That would be O(N^3) for triple, not acceptable.
Alright.
Let's produce final answer. ```python
import sys
def solve() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
N = int(data[0])
arr = list(map(int, data[1:1 + N]))
X = int(data[1 + N])
arr.sort()
for i in range(N - 2):
# optional: skip duplicate first elements
if i > 0 and arr[i] == arr[i - 1]:
continue
# if the smallest of the three is already too large, stop
if 3 * arr[i] > X:
break
target = X - arr[i]
left, right = i + 1, N - 1
while left < right:
s = arr[left] + arr[right]
if s == target:
print("True")
return
elif s < target:
left += 1
else:
right -= 1
print("False")
if name == "main":
solve()