We need to solve multiple test cases: given n items with weights w_i (positive integers up to 1e9), and a knapsack capacity W (up to 1e18). We need to select a subset of items such that total weight C satisfies ceil(W/2) <= C <= W. Output indices of selected items, or -1 if impossible.
Constraints: sum of n over test cases <= 200k, t up to 1e4. So per test case we need O(n log n) or O(n) solution.
Observation: Since we don't need to maximize, we just need any subset sum in that range.
We can consider three cases:
-
There is an item with weight >= ceil(W/2) and <= W. Then we can take that single item and done.
-
Else all items are < ceil(W/2). But then we can try to combine multiple items. Since each is positive, if we sum all items, maybe we can reach the range? But we need at most W. Since all items are less than ceil(W/2) (i.e., <= floor((W-1)/2) if W odd? Actually ceil(W/2) is the threshold: if an item >= that threshold and <= W, we would have taken it. So if no such item, then all items are < ceil(W/2). Then any subset sum is sum of numbers each less than ceil(W/2). We need to see if we can achieve a total in [ceil(W/2), W]. Since all items are < ceil(W/2), the total sum of all items may be less than ceil(W/2), then impossible. If total sum is >= ceil(W/2), we might be able to find a subset sum in that range. But note: It is possible that total sum > W, but we could take a subset that sums between ceil(W/2) and W. Since items are small relative to W, we can greedily accumulate items until total reaches at least ceil(W/2). But careful: Since we cannot exceed W, but if we add items one by one, the total will eventually reach or exceed ceil(W/2). Because each item is at most < ceil(W/2), the sum after adding an item may exceed W? It could exceed W if sum is already near W and we add another item. But we can stop before exceeding W. However, there is a possibility that the sum is already > W? Not if we start from 0 and add items, we can stop when sum >= ceil(W/2) and also sum <= W? Actually, when we accumulate items, we only add items while the total is less than ceil(W/2). So we start with total = 0, add items until total >= ceil(W/2). At that moment, total is the sum of some subset. Since each added item's weight is < ceil(W/2), the total before adding the last item was less than ceil(W/2). After adding the last item, total becomes less than ceil(W/2) + (ceil(W/2)-1) = 2ceil(W/2)-1. But we need total <= W. Since ceil(W/2) is at least half of W, we have 2ceil(W/2) -1 <= W? Let's check: If W is even, ceil(W/2)=W/2, then 2*(W/2)-1 = W-1 <= W. So total <= W-1 < W, safe. If W is odd, ceil(W/2) = (W+1)/2, then 2*((W+1)/2)-1 = W+1-1 = W. So total <= W. So after adding until total >= ceil(W/2), total is guaranteed to be <= W. Because the sum before last addition < ceil(W/2), and last item < ceil(W/2), so sum < 2ceil(W/2) <= W+? Actually we need to check maximum: before addition total < ceil(W/2), so maximum possible total before adding is ceil(W/2)-1. Add an item at most ceil(W/2)-1 (since all items < ceil(W/2)). So max total = (ceil(W/2)-1)+(ceil(W/2)-1)=2ceil(W/2)-2. For odd W: ceil(W/2) = (W+1)/2, then max total = 2*(W+1)/2 -2 = W+1-2 = W-1 <= W. For even W: ceil(W/2)=W/2, max total = 2*(W/2)-2 = W-2 <= W. So indeed total always <= W. So greedy accumulation from smallest? Actually we need any subset. So we can simply take items in any order until the sum reaches at least ceil(W/2). Since total of all items is >= ceil(W/2) (otherwise impossible), we will eventually reach or exceed the threshold. And because each item < ceil(W/2), the sum after adding will not exceed W. So that yields a valid set.
But wait: There is nuance: If the total sum of all items is >= ceil(W/2), but it's possible that the greedy accumulation may exceed W? Actually we argued it's impossible because each step we stop when sum >= ceil(W/2). At that moment, sum <= 2ceil(W/2)-2? Actually we derived max sum at that moment: before adding the last item sum < ceil(W/2), after adding the last item sum = previous_sum + w_last. Since previous_sum < ceil(W/2) and w_last < ceil(W/2), so sum < 2ceil(W/2). But we need to ensure it's <= W. For odd W, 2ceil(W/2) = 2(W+1)/2 = W+1 > W. But could sum be W+? Let's test: W=5, ceil(W/2)=3. items: [4] but 4 >= 3, case 1 would have taken it. So only if all items < 3, i.e., max weight 2. Then maximum sum after greedy: suppose items: 2,2. Before adding last item sum=2 (<3), add last item 2 => total=4, which is <=5. So max total possible is 4. Can we get sum=5? Not with items <3. So indeed sum < 2ceil(W/2) but the maximum possible sum given items < ceil(W/2) is at most 2ceil(W/2)-2. For odd W, 2*ceil(W/2)-2 = W-1. So sum <= W-1. For even W, <= W-2. So always <= W. So safe.
Thus algorithm:
For each test case:
-
Read n, W.
-
Read list w[1..n].
-
Compute threshold = (W+1)//2 (ceil(W/2)). Actually careful: ceil(W/2) can be computed as (W+1)//2 for integer W.
-
Check if any w_i >= threshold and w_i <= W. If yes, output that single item index.
-
Else, all w_i < threshold. Compute total_sum = sum(w_i). If total_sum < threshold, then output -1 (impossible).
-
Else, we need to find a subset (by indices) that sums to at least threshold. As argued, we can simply iterate through items, accumulating sum and storing indices, until sum >= threshold. Since all items are < threshold, the sum will be <= W automatically.
But is it always possible? Need to consider that there might be items that are > W? Actually if any item > W, it cannot be taken alone, but could be part of a subset? No, because exceeding W individually, but you cannot take it because its weight > W and knapsack can't hold it? The condition says we want to put some items into knapsack such that total weight C does not exceed W. So each item individually must have weight <= W? Actually the problem statement: "You want to put some of these items into the knapsack in such a way that their total weight C is at least half of its size, but (obviously) does not exceed it." It does not explicitly say that an item cannot exceed the capacity on its own. Usually in knapsack problems, you can't put an item that exceeds capacity because it wouldn't fit. But the typical interpretation: you can only select items whose individual weight is <= W? Usually yes: you cannot put an item larger than the knapsack's capacity. However, the problem statement: "their total weight C is at least half of its size, but (obviously) does not exceed it." It doesn't explicitly forbid an item with weight > W, but logically you cannot put an item that exceeds the capacity. It says "obviously" because total weight cannot exceed W, but that doesn't imply each individual weight must be <= W? If an item has weight > W, you cannot take it because then the total weight of that single item would exceed W, violating C <= W. So you cannot select such an item. So items with weight > W are simply unusable. So we must ignore those items entirely? But the problem input includes items with weight possibly > W? The constraints: w_i up to 1e9, W up to 1e18. So w_i could be > W. In example 2: "6 2" with items 19 8 19 69 9 4 - all >2 except 4? Actually 4>2, so all >2. So all items >W, so no solution. That matches.
Thus we need to handle items that are > W: they cannot be selected. So in the algorithm:
-
When looking for a single item in [threshold, W], only consider items with weight <= W.
-
In the second step, when accumulating items, we should only consider items with weight <= W, but also we already know that there is no item >= threshold and <= W. So for remaining items (weights <= W), they are all < threshold. However, some items might be > W and also > threshold; but they can't be used. So we ignore items with weight > W entirely. Also, if after ignoring those, the total sum of usable items is < threshold, then impossible. If it's >= threshold, we can accumulate them arbitrarily. However, note that if there is an item with weight > W, we cannot take it, but it may be that the only way to reach threshold is by combining items that are all <= W but some are > threshold? Actually if there is an item >= threshold but <= W, we would have taken it. So if no such item exists among all items (including those > W? Actually if an item is > W, it cannot be taken, so even if its weight is >= threshold, it's not usable. So a single-item solution only works if weight <= W. So the first step: find any i such that w_i >= threshold and w_i <= W.
-
Then for the multiple-item solution: we consider only items with w_i <= W. Among those, all have w_i < threshold (since we didn't find any in the first step). So we can proceed.
But wait: There is also possibility that some items have weight exactly = W? Then threshold = ceil(W/2) <= W. That item qualifies as single item solution (since >= threshold and <=W). So yes.
Thus algorithm: For each test case:
-
Compute threshold = (W+1)//2.
-
Initialize list of indices for answer.
-
First pass: iterate i from 1..n, if w_i >= threshold and w_i <= W: output "1\n{i}" and continue to next test case.
-
If not found, we consider items with w_i <= W. Collect their indices and weights.
-
Let usable = [(i, w_i) for i in 1..n if w_i <= W].
-
Let total_sum = sum(w_i for (i,w_i) in usable). If total_sum < threshold: output -1.
-
Else: iterate through usable items in any order, accumulating sum and collecting indices, stop when sum >= threshold. Since all weights are < threshold, the accumulated sum will be <= W (as argued). Output count and indices.
But is the order important? In some pathological case, could the greedy accumulation cause sum to exceed W before reaching threshold? Since each item is < threshold, but if we accumulate many items, sum can become > W before threshold? Wait threshold is at most W. But if we accumulate many items, sum might exceed W before it reaches threshold? That would mean total sum >= threshold, but the partial sum during accumulation might exceed W before hitting threshold. However, because we stop when sum >= threshold, we never go beyond threshold. But while accumulating, we are adding items one by one. At each step, we check if after adding the next item, the new sum >= threshold. If yes, we stop, and new sum might be > threshold. But could new sum exceed W? Let's analyze: before adding the last item, sum_prev < threshold (since we haven't reached threshold yet). The item we add has weight w <= W (and actually < threshold). So new_sum = sum_prev + w < threshold + threshold = 2threshold. As argued, 2threshold <= W+? Let's bound: threshold = ceil(W/2). So 2threshold <= W+1 (if W odd, 2ceil(W/2)=W+1; if even, =W). So new_sum < 2threshold <= W+1. However, new_sum could equal W+1? That would be when sum_prev = threshold - epsilon? Actually sum_prev < threshold, w < threshold, but sum_prev could be threshold-1, w could be threshold-1 (if threshold-1 < threshold, possible). Then new_sum = 2threshold -2. For odd W, threshold = (W+1)/2, then new_sum = 2*(W+1)/2 -2 = W+1-2 = W-1 <= W. For even W, threshold = W/2, new_sum = W-2 <= W. So maximum is less than 2threshold and integer, thus at most 2threshold - 1? But we need to check if sum_prev could be threshold-1? Actually threshold-1 is an integer if threshold is integer. So yes. And w could be threshold-1? But if w = threshold-1, then w < threshold, so allowed. So new_sum max = (threshold-1)+(threshold-1)=2threshold-2. So always <= 2threshold-2. For even W, that is W-2; for odd, W-1. So new_sum <= W-1 for odd, W-2 for even. Thus new_sum <= W-1, which is definitely <= W. But wait: Could sum_prev be exactly threshold-1? Yes if we have items that sum exactly threshold-1. Then adding a weight = threshold-1 gives total = 2*threshold-2, which is safe. So new_sum never exceeds W. So greedy accumulation is safe.
Thus algorithm is correct.
But we must also consider the case where there are items with weight > W but < threshold? That's impossible because if weight > W, then weight > W >= threshold? Not necessarily: threshold = ceil(W/2) <= W. So it's possible that an item has weight between threshold and W, but also > W? No, if > W, it's > W, so definitely > threshold (since threshold <= W). So it would not be considered as single item solution because it's > W, but it is also > threshold. However, we cannot take it. So such item is unusable. So we ignore it. Then the usable items are those <= W. Among those, none are >= threshold (since otherwise they'd be a single solution). So they are all < threshold. So same reasoning applies.
But what about the situation where there is an item exactly equal to threshold and <= W? That's covered by single case.
Thus solution works.
But is there any tricky scenario where total sum of usable items >= threshold, but greedy accumulation might exceed W because some items are exactly threshold? That cannot happen because we already checked no item >= threshold.
Edge Cases:
-
W=1: threshold = ceil(1/2)=1. Single item solution requires weight between 1 and 1. So items with weight=1 work. If no weight=1 but maybe weight=0? No weight >=1. So then all items are <=0? Not possible (w_i>=1). So if no weight=1, then all items are either >1 (i.e., >W) or <1? But weight integer >=1, so the only possibility is w_i >=1. If w_i=1 it's a solution. So if no w_i=1, then all w_i must be >=2? But then they all exceed W=1, so unusable. So total usable sum=0 < threshold=1 => impossible. So output -1.
-
W=2: threshold=1. Single item solution: any item weight >=1 and <=2 => any item weight 1 or 2. If there is weight=2, it's fine. If there is weight=1, it's also a solution? Wait, need weight >= threshold=1 and <=W=2. So weight=1 qualifies. But does taking a single item of weight 1 satisfy C >= ceil(W/2)=1? Yes, 1>=1. So it's allowed. So if there is a weight=1, we can output it. That seems okay. But wait: Is it optimal? We don't need to maximize, so yes. But is it always allowed? Because the knapsack capacity is 2, we put an item weight 1, total weight is 1, which is at least half (1). That's fine. So we could output single item weight=1. So threshold is 1.
But careful: If all items are weight=2? Then we have an item weight=2, which is >=1 and <=2, so single item solution exists. So okay.
-
Items with weight exactly 0? Not possible (w_i >=1).
-
Large W up to 1e18, but sum of weights up to n*1e9 ~ 2e14? Actually n sum across test cases is 200k, each weight up to 1e9, so total sum across all items across all tests could be up to 2e14. But W can be 1e18, so total sum may be far less. So total_sum < threshold is possible.
Now complexity: For each test case we may need to scan items twice: once to check for single item solution, and once to accumulate. Since total n sum 200k, that's fine.
But we need to be careful about memory: storing all items indices, but we can just process as we read.
Implementation approach: For each test case:
-
Read n, W.
-
Compute threshold = (W+1)//2.
-
Initialize variables: single_idx = -1, usable_items = [] (list of (index, weight) for items with weight <= W). But we also need to check for single item. While reading each weight, we can decide:
if weight >= threshold and weight <= W:
single_idx = i
if weight <= W:
usable_items.append((i, weight))
But careful: if we find single_idx, we could break early? But we need to read the rest of the line for that test case because input is line by line. We cannot skip reading remaining weights. Since we read the second line as a whole list, it's easier: read the whole list of weights first, then process.
But with large n and many test cases, it's fine to read the entire line.
Thus per test:
- read the list w (length n)
- Iterate i from 0..n-1:
if w_i <= W:
if w_i >= threshold:
single_idx = i+1 (1-indexed) and break? Actually we can break after finding one, but we must still have all w_i read. Since we already have the list, we can just scan and if find such single, we can output and continue to next test case (without further scanning maybe). But scanning is cheap.
Better: scan first to find single_idx among items with w_i <= W. If found, output that index and go next test case.
Else (no single found): we have usable items (those with w_i <= W) already considered during scanning? But we didn't store them because we might have early break. So we need to either store all usable items or re-scan. Since n total sum is 200k, we can store usable list for each test case when needed. Alternatively, we can first scan to check single, but if not found, then we need to accumulate. We could do a second pass over the list (or reuse the list) to collect usable items and accumulate sum.
But we need to output indices, so we need to know which indices are selected. So after deciding to do multiple items, we iterate through items again, collect those with w_i <= W (all are < threshold) and sum them, and also keep a running sum and selected indices until sum >= threshold.
Because we know that total sum of all items with w_i <= W is >= threshold (we need to check). But careful: total sum of all items (including those > W) might be >= threshold, but usable items sum could be less because some heavy items cannot be used. So we must compute total usable sum. So we need to either compute usable sum during first scan or second.
Simplify:
For each test case:
-
Read n, W, list w.
-
threshold = (W+1)//2.
-
single_idx = -1
-
For i in range(n):
if w[i] <= W and w[i] >= threshold:
single_idx = i+1
break
-
If single_idx != -1:
print(1)
print(single_idx)
continue
-
Else (no single item qualifies):
Now we need to consider only items with w[i] <= W (all of which are < threshold)
usable_sum = 0
selected = [] # store indices as we accumulate
cur_sum = 0
We will iterate through items again
for i in range(n):
if w[i] <= W:
usable_sum += w[i] # total sum of all usable items, for checking feasibility later
# but we also accumulate for selection as we go; however we need to know if total usable_sum >= threshold before we start? Actually we can accumulate and stop when cur_sum >= threshold. If after scanning all items cur_sum never reaches threshold, then it's impossible (because total usable_sum < threshold). But we can also compute usable_sum first then decide. Let's just compute while accumulating and break when reached threshold. If after loop not reached, output -1.
However, if we break early, we might not have computed usable_sum fully. But we only need to check if impossible: if we never reach threshold, then usable_sum < threshold (since we accumulated all usable items? Actually if we break early, we reached threshold, so fine. If we don't break early, we go through all items and cur_sum < threshold, then usable_sum = cur_sum < threshold -> impossible. So we can just do:
cur_sum = 0
selected = []
for i in range(n):
if w[i] <= W:
cur_sum += w[i]
selected.append(i+1)
if cur_sum >= threshold:
break
if cur_sum >= threshold:
print(len(selected))
print(*selected)
else:
print(-1)
But is this greedy selection (taking items in original order) always valid? As argued, we will stop once cur_sum >= threshold, and cur_sum will be <= W. But we need to ensure that we don't skip items that would make sum exceed W prematurely? Actually we only add items if they are <= W. Since all are < threshold, we are safe. But we also need to ensure that we didn't accidentally stop earlier? Actually we want to stop as soon as we reach threshold, but it's fine.
One caveat: The algorithm above adds all usable items in order until sum >= threshold. However, what if we encounter a usable item that causes cur_sum to exceed W? We argued it cannot exceed W. But let's double-check: If W is odd, threshold = (W+1)/2. Suppose we have many items each weight = threshold-1. Then after adding the first, cur_sum = threshold-1 < threshold. After adding the second, cur_sum = 2*(threshold-1) = 2threshold-2. As computed, for odd W, 2threshold-2 = W-1 <= W. So safe. So indeed cannot exceed W. So no issue.
Thus solution is straightforward.
But we must be careful with the case where there is an item that is exactly threshold? That would have been caught in the single check. So in the multiple-item phase, all w_i <= W are strictly less than threshold? Actually they could be equal to threshold if threshold <= W and w_i = threshold. But if w_i = threshold and <= W, then it would have been caught in single check because w_i >= threshold. So yes, that case is already covered. So in the multiple phase, all w_i <= W are < threshold.
Thus algorithm is complete.
But wait: Could there be a scenario where there is an item with weight exactly threshold but > W? That cannot happen because threshold <= W. So no.
Thus we are good.
Let's test the example:
-
n=1, W=3, w=[3]. threshold=2. 3>=2 and <=3, so single_idx=1 => output 1 and 1.
-
n=6, W=2, w=[19,8,19,69,9,4]. threshold=1. Check each: 19>2, so not <=W; 8>2; 19>2; 69>2; 9>2; 4>2. So no item <=W. So single_idx not found. In multiple phase, only items with w_i <=W: none. So cur_sum never reaches threshold, output -1. Correct.
-
n=7, W=12, w=[1,1,1,17,1,1,1]. threshold= ceil(12/2)=6. Check for single: items <=12 and >=6: 17>12, not; others 1<6. So none. Then multiple: items <=12: all except 17 (weight 17 >12). So usable: six 1's? Actually there are 6 ones? indices: 1,2,3,5,6,7 have weight 1. Also index 4 weight 17 excluded. So total usable sum =6. threshold=6, so we need sum >=6. Greedy: accumulate ones: after 6 items, cur_sum=6, >=6, stop. Selected indices: 1,2,3,5,6,7 (since index 4 skipped). That matches output. Note that they output 6 items: 1 2 3 5 6 7. Yes.
Thus algorithm works.
But note: Could there be a case where total usable sum >= threshold but greedy accumulation might skip some items because we might stop prematurely? No, we want to stop when sum >= threshold. That's exactly what we do. The only nuance: the order might affect the set size, but not correctness.
Now, we must ensure that the output indices are distinct and within range. Our selected list consists of distinct indices as we iterate each index once and add at most once.
Complexities: O(n) per test case.
But wait: There's a tricky case: W is huge (1e18), threshold is huge as well. Items are up to 1e9. So total sum of usable items might be less than threshold even if there are many items. So we need to compute total sum as we accumulate? Our approach: we accumulate until we reach threshold; if we finish loop without reaching threshold, then we output -1. But if we never reach threshold but total sum is >= threshold, that would be impossible because we would have stopped when sum >= threshold. So if we never stop, total sum is < threshold. So it's fine.
But what about the possibility of overflow? In Python, integers are arbitrary precision, so fine.
Now, consider memory: we need to store the whole list w for each test case because we may need to iterate twice? Actually we can process in one pass if we want to avoid storing all w. Since we first need to check for single item, we could read items one by one, and if we find a single, we can output and then skip the rest of the items (by reading but ignoring). But it's simpler to read the whole list.
Given total n is 200k, storing lists is fine.
But be careful with input reading speed: use sys.stdin.buffer.read() and parse ints.
We'll implement a fast input parser.
Now, what about the case where there is a single item with weight between threshold and W but we might also have multiple items that sum to exactly something? We just output the single item. That's allowed.
Edge Cases:
-
n=0? But n>=1 per constraints.
-
Items exactly equal to W: single solution.
-
Items with weight exactly threshold: single solution.
-
Items with weight 0? Not allowed.
Now, but is there a scenario where there is no single item, but the only way to achieve the range is with items that individually exceed W? No, because any item exceeding W can't be taken.
Thus answer -1 if total usable sum < threshold.
But wait: There is also the possibility that the total sum of usable items is >= threshold but we might not be able to form a subset sum in the range because all items are large? But they are all < threshold, so as argued the greedy works.
But we should also consider that the sum of items we take might exceed W? Already argued it won't happen.
Thus solution stands.
But let's double-check the proof: Given a set of positive integers each less than T = ceil(W/2). Suppose sum of all elements S >= T. Then there exists a subset whose sum lies in [T, W]. We claim that the greedy algorithm (taking items in any order until sum >= T) yields such a subset. Proof: Let the prefix sums after adding items be P_k = sum_{i=1..k} a_i. Since each a_i < T, and P_{k-1} < T (otherwise we would have stopped earlier), we have P_k = P_{k-1} + a_k < T + T = 2T. And since T = ceil(W/2), we have 2T <= W+1? Actually for odd W, 2T = W+1, so P_k <= W? Wait P_k is integer, and we have P_k < 2T, so P_k <= 2T - 1. For odd W, 2T -1 = W, so P_k <= W. For even W, 2T = W, so P_k < W, so P_k <= W-1. So indeed P_k <= W. So the subset sum is <= W. Also it is >= T by construction. So valid.
Thus algorithm is correct.
Now, implement.
But we must also consider the output format: For each test case, if solution exists, print m and then the indices. They should be distinct and presumably in any order. Our list is in the order we added them. That's fine.
Now, about printing -1: Just a single line -1.
Potential pitfalls:
-
If there is a single item that satisfies condition but also is part of multiple items? We choose the single item.
-
Need to ensure that we output indices starting from 1.
-
Large input: Use sys.stdout.write for efficiency.
I'll code:
import sys
def solve():
data = sys.stdin.buffer.read().split()
it = iter(data)
t = int(next(it))
out_lines = []
for _ in range(t):
n = int(next(it))
W = int(next(it))
w = [int(next(it)) for __ in range(n)]
threshold = (W + 1) // 2
# Look for a single item
single_idx = -1
for i, weight in enumerate(w):
if weight <= W and weight >= threshold:
single_idx = i+1
break
if single_idx != -1:
out_lines.append("1")
out_lines.append(str(single_idx))
continue
# else, try to accumulate
cur_sum = 0
selected = []
for i, weight in enumerate(w):
if weight <= W: # only consider usable items
cur_sum += weight
selected.append(i+1)
if cur_sum >= threshold:
break
if cur_sum >= threshold:
out_lines.append(str(len(selected)))
out_lines.append(" ".join(map(str, selected)))
else:
out_lines.append("-1")
sys.stdout.write("\n".join(out_lines))
if name == "main":
solve()
But we need to be careful: When we break after finding a single item, we do not process the rest of the items in that test case. However, we have already read all w values, so it's fine.
But one nuance: In the second pass, we iterate over all w again. But if we already used a single_idx, we skip this. So fine.
However, there is a subtle case: Suppose we find a single item weight exactly threshold? That's fine.
Now test with custom cases:
Case: t=1, n=3, W=5, w=[3,3,3]. threshold=3. Here item1 weight 3 >=3 and <=5, so single_idx=1. Output "1\n1". That's valid.
But note: Could also take two items: 3+3=6 >5, invalid. So single is best.
Case: n=2, W=5, w=[2,4]. threshold=3. Check single: 2<3, 4>=3 and <=5 -> single_idx=2, output "1\n2". correct.
Case: n=2, W=5, w=[2,2]. threshold=3. no single. usable both 2 <=5, sum=4 >=3. Greedy: add first 2 -> cur_sum=2<3, add second -> cur_sum=4>=3, selected indices 1,2. output "2\n1 2". sum=4 <=5, ok.
Case: n=2, W=5, w=[2,3]. threshold=3. Check single: 2<3, 3>=3 -> single_idx=2. So output 1 2? Actually index 2 weight 3 qualifies. So output "1\n2". That's also acceptable (sum=3). But note that 3 is exactly threshold. fine.
Case: n=3, W=10, w=[6,6,6]. threshold=5. Check single: 6>=5 and <=10 -> single_idx=1. Output single.
But also multiple would be possible: two 6s sum to 12>10 invalid, so only single.
Case: n=3, W=10, w=[5,5,5]. threshold=5. Check single: 5>=5 and <=10, so single_idx=1. Output single.
Case: n=3, W=10, w=[1,4,6]. threshold=5. single: 6 qualifies, output index3.
Case: n=3, W=10, w=[4,4,4]. threshold=5. no single (4<5). total sum=12>=5. greedy: first 4 (cur=4<5), second 4 (cur=8>=5) -> selected indices 1,2 sum=8 <=10. ok.
Case: n=3, W=10, w=[4,4,6]. threshold=5. single: 6 qualifies, output index3.
Case: n=3, W=10, w=[11,11,11]. all >W, so no single, no usable. cur_sum=0<5 => -1. correct.
Case: n=3, W=10, w=[11,1,1]. threshold=5. Check single: 11>10 so not considered, 1<5, 1<5, so no single. usable: indices2,3 (weights 1,1) sum=2 <5 => -1. However total sum of all items =13>5 but includes unusable weight 11. So -1 correct.
Now consider W=1e18, threshold=5e17+? Actually (W+1)//2. Items are 5e17-1? But all less than threshold. If we have many items each weight = 1e9, we would need about 5e8 items to reach threshold, but n max is 2e5, so if W huge, it's likely impossible unless there is a large single item. But we need to handle large numbers, Python ok.
Now, there is a nuance: When we break after finding single, we must ensure we consume the rest of input? Already we read the whole line, so fine.
Now, what about scenario where there is an item with weight exactly threshold but > W? impossible.
Now, check if there is any scenario where using multiple items could lead to sum in [threshold, W] but greedy accumulation may exceed W due to large items? But we already argued it's impossible because each item is < threshold. But consider items that are not all < threshold: Actually if we are in the multiple branch, we have already checked that no single item with weight >= threshold and <= W exists. However, it's possible that there is an item with weight > W but < threshold? That's impossible because if weight > W, then weight > W >= threshold? Actually threshold <= W, so if weight > W, it is automatically > threshold, so such item would be > threshold. So it would not be in the multiple branch because we only consider items <= W. So all items considered in multiple branch are <= W and also < threshold. So safe.
Thus solution stands.
But wait: Is there any scenario where an item weight is exactly W but W < threshold? That's impossible because threshold <= W always. So weight W is >= threshold.
So all good.
Time complexity: O(total n) ~ 200k, which is fine.
Now we should produce final answer.
But note: The problem statement says "Output the list of items you will put into the knapsack or determine that fulfilling the conditions is impossible. If there are several possible lists of items satisfying the conditions, you can output any. Note that you don't have to maximize the sum of weights of items in the knapsack." So our solution is correct.
Double-check the example: Provided output matches.
Thus we are done.
Potential improvements: None.
Now we must output in required format: each test case result on separate lines. In our code, we collect out_lines and join with newline.
Be careful: If we output multiple lines per test case, we need to separate them properly.
Test with sample:
Input:
3
1 3
3
6 2
19 8 19 69 9 4
7 12
1 1 1 17 1 1 1
Our algorithm:
Test1: single 3 -> out_lines: "1","1"
Test2: no single, usable sum 0 < threshold=1 -> after loop cur_sum=0 -> -1 -> out_lines append "-1"
Test3: no single, usable: six ones, after 6 items cur_sum=6 >=6, selected indices 1,2,3,5,6,7 -> out_lines append "6", then "1 2 3 5 6 7"
So final out_lines: ["1","1","-1","6","1 2 3 5 6 7"] -> join with newline ->
1
1
-1
6
1 2 3 5 6 7
Matches sample.
Now note: The sample output has a blank line? Actually sample:
Output
1
1
-1
6
1 2 3 5 6 7
No extra blank lines. So fine.
Thus solution.
But wait: Did we handle the case where the total usable sum is >= threshold but the greedy accumulation might skip some usable items because we stop early? That's fine.
Now consider edge case: n=200000, all weights = 1, W=200000 (so threshold=100000). Then total usable sum = 200000 >= threshold. Greedy accumulation will take first 100000 items (since after 100000 items sum=100000 >= threshold). That's okay.
But what about W = 10^18, items up to 10^9, threshold huge (5e17+?). The greedy will need to accumulate many items, potentially more than n, but if total sum < threshold then -1. So that's okay.
Now, we need to be cautious about Python recursion? Not needed.
Thus final code.
But I see a potential pitfall: Our multiple-item selection loop stops at the first time cur_sum >= threshold. However, it's possible that we skip some items that are > W? But we already filter by weight <= W. Also we might include an item that is > threshold? No, because we are in else branch where no such item exists. So all items we consider have weight < threshold. But what if we have an item that is exactly threshold? That would have been caught earlier. So okay.
Now, we must ensure that we don't inadvertently skip items that are > W but are later in the list? Not relevant.
Now, the solution is correct.
But let's think about some tricky test:
Case: n=3, W=4, w=[2,2,3]. threshold=2 (since ceil(4/2)=2). Check single: any item weight >=2 and <=4? 2 qualifies? Yes, weight 2 >=2 and <=4, so single_idx=1. So output 1. But note that 2 is exactly threshold; acceptable. However, what about item 3? Also qualifies, but we output first.
Now case: n=3, W=4, w=[3,3,3]. single: 3 qualifies, output index1.
Now case: n=3, W=4, w=[1,3,3]. single: 3 qualifies, index2.
All good.
Now, case where there is a single item with weight exactly threshold but also we might want to consider multiple items? Doesn't matter.
Now, there might be a nuance: The problem says "C should satisfy: ⌈ W/2⌉ ≤ C ≤ W." So if we have an item exactly threshold, C = threshold, which is acceptable. So fine.
Now, consider W=0? Not allowed (W>=1).
Now, double-check rounding: ceil(W/2) for integer W: (W+1)//2 works for all positive integers.
Now, what about items with weight 0? Not allowed.
Now, what about items with weight exactly equal to W? That's fine.
Now, we should produce final answer.
But there is a possible alternative: Use any subset, not necessarily prefix. Our greedy is prefix; that's okay.
Now, implement.
Potential performance improvements: Instead of storing all w list, we could process streamingly. But storing is fine for total 200k ints.
Now, code.
But I'll also check for any missing case: what about the scenario where there is an item with weight > W, but also there is a combination of other items that sum to within range. Since we ignore items >W, it's fine.
Now, let's consider if there is an item exactly = threshold but it's >W? impossible.
Now, we must ensure we don't output an empty list. The problem says if there exists solution of m items, print m and then the indices. m should be >=1? Possibly m=0? But C=0 would not be >= ceil(W/2) unless W=0, so no.
Now, all good.
But there's one more nuance: In the multiple-item case, we are accumulating all usable items in order. However, suppose we have an item that is <=W but > threshold? No, we eliminated that.
But what if there is an item with weight exactly threshold but we didn't catch it because we miscomputed threshold? No.
Now, is there any scenario where the total sum of all usable items is >= threshold, but the greedy accumulation (taking items in order) might reach a sum that is less than threshold but then add an item that pushes sum to > W? Let's test: Suppose threshold = 5, W=6. Items: [2,4]. All <5? 4 <5, 2<5. Greedy: take 2 -> sum=2<5, then take 4 -> sum=6. 6 <= W? Yes, W=6. So ok. Suppose W=5, threshold=3. Items: [2,4]. But 4 is >=3, so single item case. So not multiple.
Now, try to construct: W=7, threshold=4. Items: [3,5]. But 5>=4 and <=7 -> single. So not multiple. Items: [3,3,3]. All <4. Greedy: 3->3<4, 3->6 >=4, sum=6 <=7. Good. Items: [2,2,2] sum=6 >=4, but each <4. Greedy: after 2+2+2=6, ok. Items: [1,1,1,1,1] sum=5, threshold=4, greedy: 1+1+1+1=4, stop, sum=4, ok.
Thus fine.
So solution is correct.
Now, code.
But there is one more nuance: The problem statement says "the i-th one has weight w_i." And we need to output indices. We are using 1-indexing.
Now, implement.
I'll produce final solution with fast I/O.
Edge Cases: t up to 1e4, but sum n 200k, so many small test cases. Our code does two passes per test case if no single found. That's okay.
But we could do a single pass: as we read items, we can store usable items, and also check for single. But we need to know threshold first, which we have. So we can process in one pass: Read n and W, compute threshold, then as we read each weight, we can check for single; if found, we can record index, and then we need to skip reading remaining weights of the test case? But we still need to consume them from input. If we break early from reading, we would mess up the input stream. So we must still read them. So it's simpler to read the whole list.
But we can read all weights into list w, then process.
Given constraints, it's fine.
Now, we should also consider memory: For each test case we store w list, but we can process on the fly if we do two passes? Not possible without storing or reading twice. But we can store usable items only. Actually we could read the entire line into a list of ints; that's the same memory.
Since sum of n is 200k, storing one list per test case sequentially is fine.
Now, final code:
def solve():
import sys
data = sys.stdin.buffer.read().split()
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
n = int(next(it))
W = int(next(it))
w = [int(next(it)) for __ in range(n)]
thr = (W + 1) // 2
single = -1
for i, wt in enumerate(w):
if wt <= W and wt >= thr:
single = i+1
break
if single != -1:
out.append("1")
out.append(str(single))
continue
cur = 0
selected = []
for i, wt in enumerate(w):
if wt <= W:
cur += wt
selected.append(i+1)
if cur >= thr:
break
if cur >= thr:
out.append(str(len(selected)))
out.append(" ".join(map(str, selected)))
else:
out.append("-1")
sys.stdout.write("\n".join(out))
Now, I will produce final answer with explanation.
But before finalizing, let's test with some random cases using brute force for small n to ensure algorithm never fails.
We can write a small tester:
For random small n (1..10), random W (1..30), random weights (1..30), compute all subsets, check if any subset sum in [thr, W]. If exists, our algorithm should find one. If not, output -1.
I can simulate mentally, but I trust.
One more scenario: Suppose there is an item with weight > W but there are enough other items to meet threshold, but we ignore that > W item. Our algorithm picks only those <=W. That's correct.
Now, also consider if there is an item with weight exactly W but also there are smaller items; single item solution exists, we output it.
Now, consider case where there is no single item, but there exists a subset that sums to exactly W, but our greedy might stop earlier when sum reaches threshold, which could be less than W. That's fine; we don't need to maximize.
Now, consider case where total usable sum is >= threshold, but the greedy picks a set that sums to something > W? We argued impossible. But let's check extreme: W=10, threshold=5, items: [6,?] but 6>=5, so single. So not.
Items: [5,?] but 5>=5, single.
Items: [4,4,4] -> we already saw sum 8 <=10.
Items: [4,4,3] -> greedy: order maybe 4 then 4 sum=8>=5 stop. sum=8 <=10.
Items: [4,3,3] -> 4+3=7.
Items: [2,2,2,2,2] -> sum=10 if take all? But we stop at 2+2+2+2? Actually threshold=5, so after 3 items sum=6>=5 stop. sum=6 <=10.
Thus safe.
Now, consider threshold near W: e.g., W=100, threshold=50. Items: [49,49]. Both <50. Sum after two =98 <=100. Good.
W=101, threshold=51. Items: [50,50]. Both <51? Actually 50 <51. Sum=100 <=101. Good.
W=101, threshold=51, items: [50,51]. But 51>=51, single.
W=101, threshold=51, items: [50,50,50]. Greedy: after two sum=100>=51 stop, sum=100 <=101.
Now, consider W=3, threshold=2, items: [1,1,1]. Sum after two=2>=2 stop, sum=2 <=3.
W=4, threshold=2, items: [1,1,1] -> after two sum=2 stop, fine.
Now, what about items that are exactly threshold-1 but we might need more than two? It's fine.
Now, all seems consistent.
Thus final answer.
But let's also consider a tricky scenario: W=6, threshold=3. Items: [2,2,2]. Greedy: after two sum=4>=3 stop, sum=4 <=6. Good. However, there is also a subset sum=6 (all three) but we don't need it.
Now, I think it's fine.
Now, just to be thorough: The problem statement says "If there are several possible lists of items satisfying the conditions, you can output any." So we can output any.
Now, check constraints: sum n over test cases <= 200000, so our O(total n) algorithm is fine.
Now, we might consider memory: out list might become large but total output size is O(total n), which is fine.
Now, final code.
But I want to double-check the reading method: using data = sys.stdin.buffer.read().split() reads all input into memory. Total numbers: t up to 1e4, each test case has n+2 numbers. Sum n <=200k, so total numbers <= 200k + 2*1e4 = 220k approx, which is fine. So splitting all is okay.
Now, produce final answer with explanation.
But we must also include explanation in the final output? No, just code.
Now, I'll write final answer.
But note: The problem might require printing -1 as a separate line, not " -1". That's what we do.
Now, I think done.
Wait, there's another nuance: In the first pass to find single item, we break as soon as we find one. However, there might be multiple. That's fine.
Now, think about possible error: In the multiple branch, we use the same list w but we didn't exclude the items that are > W? We check condition weight <= W before adding. So it's fine.
Now, check for scenario where a single item is found but we break early; we didn't process the rest of items in the list (i.e., we skip reading? No we already read all w, so the iterator has already consumed all numbers. So we are okay.
Now, final answer.
But before concluding, I'd like to consider a potential counterexample from similar problems: There's a known Codeforces problem "Knapsack" (CF Round 730? Actually problem: "Knapsack" from Codeforces Round #1498? Something like: find subset with sum between ceil(W/2) and W. The solution is exactly: either take a single element if any >= ceil(W/2) else take elements greedily because all are < ceil(W/2) and total sum >= ceil(W/2). Indeed I've seen that. So it's correct.
Now, output as described.
Thus final answer is ready.
Now, I'll write the solution explanation.
But for the response, I need to output the code. The user asked "You have a knapsack ..." They likely want code. So I will output the solution in Python.
I'll include comments.
Now, produce final answer. ```python
import sys
def solve() -> None:
data = sys.stdin.buffer.read().split()
it = iter(data)
t = int(next(it))
out_lines = []
for _ in range(t):
n = int(next(it))
W = int(next(it))
w = [int(next(it)) for __ in range(n)]
threshold = (W + 1) // 2 # ceil(W/2)
# 1) Check for a single item that fits alone
single_idx = -1
for i, weight in enumerate(w):
if weight <= W and weight >= threshold:
single_idx = i + 1 # convert to 1‑based index
break
if single_idx != -1:
out_lines.append("1")
out_lines.append(str(single_idx))
continue
# 2) No suitable single item → try to combine many small items
cur_sum = 0
selected = []
for i, weight in enumerate(w):
if weight <= W: # ignore items that don't fit even alone
cur_sum += weight
selected.append(i + 1)
if cur_sum >= threshold:
break
if cur_sum >= threshold:
out_lines.append(str(len(selected)))
out_lines.append(" ".join(map(str, selected)))
else:
out_lines.append("-1")
sys.stdout.write("\n".join(out_lines))
if name == "main":
solve()