We need to parse the problem carefully.
We have n songs, each with pleasure a_i and duration t_i. Sasha starts at some song index x (1-indexed) and listens sequentially: x, x+1, ..., up to n, but stops when total time spent reaches k (minutes needed to work) OR when he reaches last song.
He can listen to songs either fully or partially. For partial listening, he must listen at least ceil(t_i/2) minutes? The problem says: "listens to it for no less than ⌈ d/2 ⌉ minutes, then he immediately switches to the next song." Actually: "if the length of the song equals d minutes, Sasha listens to it for no less than ⌈d/2⌉ minutes?" Let's read: "Formally, if the length of the song equals d minutes, Sasha listens to it for no less than minutes". The image likely indicates ceiling(d/2). So yes, at least ceil(d/2). It says "integer number of minutes, at least half of the song's length." Since it says integer number of minutes, we take ceil(d/2). So partial listening time for song i is p_i = ceil(t_i/2) (minimum). He can also listen to it fully: time = t_i.
But he can also listen to a song fully? The description: "Sasha can listen to each song to the end or partly." So two modes: full (listens entire t_i) or partial (listens at least ceil(t_i/2) and then stops). However, the partial mode: he listens for exactly some integer minutes? The wording: "Sasha listens to it for integer number of minutes, at least half of the song's length... then he immediately switches it to the next song (if there is such)." It doesn't say he must stop exactly after that amount; he can listen more? But if he listens more than ceil(d/2) but not full, does that count as partly listened? The condition "listens to it for integer number of minutes, at least half of the song's length" and then switches. I think he can listen any integer amount from ceil(t_i/2) to t_i-1? But the problem says "listens to the song for integer number of minutes, at least half of the song's length, then he immediately switches it to the next song". That suggests he doesn't listen to the full song; he stops early. So the partial listening mode is to listen for exactly some integer minutes >= ceil(t_i/2) and < t_i. However, if he listens exactly t_i, that's full mode. But could he listen for a duration in between? The problem might not restrict that; but it does say "listens to it for integer number of minutes, at least half of the song's length, then he immediately switches it to the next song (if there is such)." If he listens to the full song, he would let it finish and then switch. That is also a switch but after full. So partial means he stops before the song ends. The key is that Sasha can decide for each song whether to listen fully or partially, with the constraint that at most w songs can be listened partially. Also if a song is partially listened, the time spent on it must be at least ceil(t_i/2). But is there any benefit to listening more than ceil(t_i/2)? Since pleasure is the same regardless, the only reason to listen more would be to consume time without getting extra pleasure. That would be suboptimal because you could instead stop earlier and move to next song (which might give pleasure if you have time). However, you cannot stop earlier than ceil(t_i/2) because that would violate partial listening rule. So the optimal for a song that you decide to partially listen is to spend exactly ceil(t_i/2) minutes, because spending more only consumes time without extra pleasure, and you could use that time to (maybe) listen to later songs to get pleasure. Therefore, we can assume that partial listening always uses exactly ceil(t_i/2) minutes. Similarly, full listening uses t_i minutes.
Now there is also the case of the last listened song: "If the last listened song plays for less than half of its length, then Sasha doesn't get pleasure from it and that song is not included to the list of partly listened songs." Wait, this is about the situation where he runs out of time before completing half of a song? Let's parse: He listens to songs sequentially until he reaches work (i.e., total time used reaches k) or until he listens to last song. He may stop in the middle of a song if time runs out. However, the rules say: He can listen to each song to the end or partly. In the second case (partly), he must listen at least ceil(t_i/2) minutes. So he cannot stop a song before ceil(t_i/2) minutes, unless that song is the last one? But the description of partial listening says he listens for integer number minutes, at least half, then switches. But what if he doesn't have enough time left to listen even ceil(t_i/2) minutes? Then presumably he cannot start that song at all? Because if he starts it, he must listen for at least that many minutes (since partial requires at least half, but if he stops earlier because time runs out, then he didn't meet the condition). However, the problem also says: "If the last listened song plays for less than half of its length, then Sasha doesn't get pleasure from it and that song is not included to the list of partly listened songs." This suggests that it's possible that the last song he listens to (the one where time runs out) might be listened for less than half of its length. In that case, he doesn't get pleasure from it, and importantly, it does not count towards the w limit (since it's not considered partly listened? Actually says "that song is not included to the list of partly listened songs." So if he listens to less than half, it's not considered a partial listen for the purpose of the w constraint, but he also gets no pleasure. That seems like a scenario where he starts a song but then runs out of time before even half. But is he allowed to start a song if he knows he won't have time to listen to at least half? The problem says: "He listens to songs until he reaches the work or until he listens to the last song in his playlist." That implies he continues playing songs sequentially; when time runs out, he stops possibly in the middle of a song. So it's allowed to have a final incomplete song that may have listened less than half. However, does that count as a "partly listened" song? The problem clarifies that if the last listened song is less than half, then it's not considered partly listened for the w limit. But what if he listens to more than half but less than full? That would be considered a partial listen? Actually the partial listening mode requires listening at least half and then switching. So if he stops before the end because time runs out, but he has already listened at least half, does that count as a partial listen? According to the rules, partial listening is a deliberate choice to stop after at least half, but if time runs out after listening at least half, that is still partial? The problem likely treats any song that is not listened to fully as partially listened if the listening time is at least half. But there's a special case: the last song might be cut short before half; then it's not counted as partly listened (and no pleasure). For the w constraint, we need to count songs that we deliberately partially listened to, but if we are forced to stop early due to time and it's less than half, it doesn't count. However, we could also plan to have a final song that we only listen to partly (>= half) but we might run out of time after exactly half? Actually if we run out of time exactly at the half point, we get pleasure and it's partial. So the distinction: any song that we stop before its full length, we either have listened >= ceil(t_i/2) (partial) or < ceil(t_i/2) (incomplete, no pleasure). The incomplete case only can happen for the very last song we attempt (due to time running out). So we need to handle that.
Thus overall: Sasha chooses a starting index x, and then a set of at most w songs (from those he actually listens to) to be partially listened (i.e., he will listen exactly ceil(t_i/2) minutes), except possibly the last song if it's incomplete (< half). All other songs he listens fully (t_i minutes). But he can also decide to listen a song fully even if it's among the w? The w is an upper bound on songs listened partly, not a requirement to use partials. So he can choose to listen any song fully, regardless of w. The only constraint is that number of partial songs (listened at least half but not full) is at most w. And if the last song is incomplete (< half) it's not counted as partial.
Goal: maximize sum of a_i for songs that are listened to at least half (i.e., full or partial) except those incomplete last song. Also, the total time spent must be ≤ k (actually exactly k? It says: "He listens to songs until he reaches the work or until he listens to the last song." So he stops when the travel time reaches k? Actually: "Sasha reaches the work by car. It takes exactly k minutes. On his way he listens to music." So the car ride lasts exactly k minutes. He listens until he reaches work. So he stops exactly when total listening time reaches k? But if he finishes a song exactly at the moment he arrives? The description: "He listens to songs until he reaches the work or until he listens to the last song." That suggests he stops either when time runs out (reaches work) or when no songs left. When the travel ends, he stops listening, even if in the middle of a song. So the total time spent listening is at most k (could be less if he runs out of songs). But typically we consider that he listens for a total duration that does not exceed k. So we need to maximize total pleasure from songs that are at least half listened, with total time <= k, with at most w partial songs (where partial songs count as half time: ceil(t_i/2)), and full songs count full t_i.
Additionally, we must consider that the sequence is contiguous starting from x. So we are selecting a contiguous subsequence from some start index x to some end index y (y may be determined by time constraint), but within that contiguous block, we can decide which songs to listen partially, subject to at most w partials. The incomplete last song can be a song that we started but didn't get to half; we may get no pleasure, and it doesn't count as partial. That effectively means that we might be able to start a song even if we don't have time to listen half of it, but then we waste time without gaining pleasure. Is that ever beneficial? Possibly if we have time left that is less than half of next song, we could either skip it entirely (i.e., stop before starting it) and thus have unused time, or start it and waste that time but not gain pleasure; that would never increase pleasure, so it's suboptimal. So we would never intentionally start a song if we can't listen to at least half of it. However, if the sum of times of fully listened songs plus partial half-times exactly fits within k, we might end exactly at the end of a song. If we have leftover time that is less than half of the next song, we wouldn't start it because it would give no pleasure. So the optimal solution will have total listening time <= k, and the next song (if any) would require at least ceil(t_{next}/2) time to get pleasure, but we won't start it because we can't get pleasure; but if we start it and listen for some minutes < half, we waste time without pleasure, which is not beneficial. Therefore, we can assume that we only include songs for which we listen at least half, except possibly the last song which we may not get to half due to time constraint, but we would rather not include that song. So effectively, we can assume the listening set is a prefix of the sequence from x, where each included song is either fully or partially listened, with total time <= k, and at most w partials. And we can stop before a song if we can't get at least half.
But wait: There's also the scenario where we might want to partially listen a song that we would otherwise not be able to include fully because of time, but by partially listening we can include it and get pleasure. So that's the trade-off: partial listening reduces time per song (half-ish) at the cost of using one of the w slots. So we need to decide which songs to partially listen to maximize sum of a_i given time constraint.
This is reminiscent of selecting a contiguous subarray (starting at some x) and choosing up to w items to "half" their time. However, note that partial listening reduces time to ceil(t_i/2). But does it affect pleasure? No, pleasure remains a_i.
Thus, effectively, for each song i, we have two possible "costs": full cost = t_i, partial cost = h_i = ceil(t_i/2). We can use at most w partial selections. And we must select a contiguous segment starting at some x, and we must include songs in order, and we must decide for each song in the segment whether to take it fully or partially (if we have partial quota left) to maximize sum a_i subject to total cost ≤ k. Additionally, we cannot skip songs: we must include every song from x to some y (contiguous) if we decide to include them; but we can decide to stop before y+1. However, we could also decide to not include a song after some point? Actually we must listen sequentially; we cannot skip a song. So if we decide to include song x, we must either listen to it fully or partially (or if time runs out during it and we don't get half, we get no pleasure). But we could also decide to stop before starting song x+1 if we don't have time. So yes, the selected songs form a prefix of the sequence starting at x. So we need to choose start index x and then decide how many songs to include (some prefix length L) and which of those to make partial (up to w) to maximize total pleasure under time constraint.
This is similar to sliding window problems with two types of cost. Since n up to 2e5, we need O(n log n) or similar.
We need to consider each possible starting point? Could be O(n) with two pointers if we can maintain the best selection of partials within the window. But the choice of which songs to partially listen within the window is not fixed; we want to minimize total cost for a given set of songs (to include as many as possible) or maximize sum for a given time. Typically, for a given contiguous segment, we would want to partially listen to those songs with the greatest reduction in time (i.e., t_i - h_i) per song, because using a partial slot on a song reduces its cost by d_i = t_i - ceil(t_i/2). The time saved by making a song partial is d_i. So for a given set of songs we want to include, to fit within time k, we need to ensure that sum of full costs minus sum of d_i for partial selections <= k. Or more directly, to include a segment, we need to be able to cover the total cost with up to w partial selections.
If we fix a segment [l, r], we can compute the total time if we take all songs fully: T_full = sum_{i=l}^r t_i. Then we can choose up to w songs to partially listen to, which reduces the total time by the sum of d_i for those songs. So the minimal possible total time for that segment given up to w partials is T_full - sum of the largest d_i among the segment (up to w). So we need T_full - sum_{top w d_i in [l,r]} <= k. And we want to maximize sum of a_i in the segment. So for each segment, we can check if it's feasible.
Then the problem reduces to: find maximum sum of a_i over any contiguous subarray such that total full time minus sum of up to w largest d_i in that subarray <= k. And we also consider the possibility that we might stop in the middle of a song (incomplete), but as argued, it's never beneficial to include a song partially (since if you can't even afford half, you get no pleasure; if you can afford half but not full, you might choose partial). The incomplete case could be beneficial if you have some leftover time that is less than half of the next song; you could start it and listen for that leftover time but you get no pleasure, so not beneficial. So ignore.
But wait, there is also possibility to not use partial on some songs even if they are in the segment; we always have the option to use up to w partials. So to minimize time for a given segment, we want to use partials on the songs with largest d_i, up to w. So the condition for feasibility is that the minimal possible time (by using best partials) <= k. And we want maximize sum a_i.
So the problem becomes: maximize sum_{i=l}^r a_i subject to sum_{i=l}^r t_i - sum_{top w d_i in [l,r]} <= k.
But we also need to consider that partial selections are limited to at most w, but we may use fewer if that helps? Actually if we use fewer partials, the time is larger, so it's not helpful for feasibility; we would always want to use as many partials as needed to reduce time, up to w. However, there might be cases where using a partial on a song reduces time but also uses a partial slot; if we have more than w high-d_i songs, we can only use w. So the minimal time is as described.
Now we need to find the max sum over all subarrays that satisfy that inequality.
But note: the segment must start from some x and go forward; but it doesn't need to be contiguous? Actually yes, we listen in order; we cannot skip songs. So subarray.
Now the twist: the starting song x is chosen arbitrarily; but the subarray must be from x to some y >= x. So we need to consider all subarrays. So it's maximum sum over any contiguous subarray meeting the condition.
But is there any additional constraint about the number of partial songs being at most w, but if we partially listen to a song we must listen at least half; that we already accounted. The condition seems correct.
But we must also consider that we may choose not to fully include a song if we can't afford even its half time? Actually, if we consider a segment [l, r], we are assuming we include all songs from l to r, and for each we either take full or partial. However, it's possible that the optimal solution might skip the last song because we can't afford even its half time, but we could include earlier ones and then stop. That's equivalent to considering subarray [l, r] where r is the last song we fully/partially listen. So any feasible solution corresponds to a subarray where we include all songs in that range, with partial selections as needed, and total time <= k. So our reduction is valid.
But there is also scenario where we might include a song with partial listening, but the time saved by partial might be such that we can include an extra song with partial? That's captured by the condition.
Thus, we need to compute for each subarray its sum a, sum t, and the sum of the largest w values of d_i in that subarray. Then check if sum t - sum_{top w d_i} <= k. Maximize sum a.
n up to 2e5, w up to n, k up to 2e9. a_i up to 1e4, t_i up to 1e4, d_i = t_i - ceil(t_i/2). ceil(t_i/2) = (t_i+1)//2. So d_i = t_i - ceil(t_i/2) = floor(t_i/2). Actually t_i - ceil(t_i/2) = floor(t_i/2). Because if t_i even: t_i/2 exactly, so ceil = t_i/2, d_i = t_i/2 = floor(t_i/2). If odd: t_i=2m+1, ceil = m+1, d_i = 2m+1 - (m+1) = m = floor(t_i/2). So d_i = floor(t_i/2). Good.
Thus partial cost = ceil(t_i/2) = t_i - d_i. And full cost = t_i. So using a partial reduces time by d_i.
So the condition is: sum_{i in segment} t_i - sum_{top w d_i in segment} <= k.
Let S_t = sum t_i, S_d_top = sum of largest w d_i in segment (if segment length L < w, then sum of all d_i). Then condition: S_t - S_d_top <= k.
Equivalently, S_t - S_d_top = sum of minimal costs given we can use at most w partials. This minimal cost is sum over i of min(t_i, ceil(t_i/2)? Not exactly; it's: we can choose up to w songs to pay ceil(t_i/2), others pay t_i. That's like: total = sum t_i - sum_{chosen} d_i. So we want to maximize reduction.
We need to efficiently handle sliding window to compute max sum a satisfying condition.
Idea: Use two pointers (sliding window) where we expand right pointer, and maintain window [l, r]. For each l, we try to expand r as far as possible while condition holds, and track max sum a. However, the condition involves sum t and sum of top w d_i within window, which is not trivial to maintain dynamically with a two-pointer because removing left element requires updating a data structure for top w d_i. But we could use a data structure that supports insert/delete and query sum of top w values. This can be done with two multisets (like two heaps) for maintaining k largest elements. Since w is up to n, but sum of top w d_i changes when window changes. We can maintain two multisets: one for the largest w d_i (call set "top") and the rest ("bottom"). For each window, we compute total t and total a. Then we check condition: total_t - sum_top_d <= k. As we slide, we need to update these structures.
But careful: w is the maximum number of partial songs we can use. However, if the window length is less than w, we can partially listen to all songs, so sum_top_d is sum of all d_i in window. In that case, we maintain top set as all elements, but we need to consider up to w. In the two-set approach, we maintain exactly w largest? Actually we want sum of up to w largest. If window size < w, we want sum of all d_i. So we can maintain a structure that keeps the largest min(w, window_size) values? Or we can maintain two sets: one for selected (largest w) and one for the rest. But if window size less than w, then selected would contain all elements, and sum_top_d = total_d. That works if we always keep exactly w elements in selected when possible, but if window size < w, we keep all. For dynamic maintenance, we need to ensure when we add an element, we decide whether it belongs to selected (top) or not. Standard approach: maintain a multiset for the largest w elements, but when window size < w, we simply add all new elements to selected and they stay there. When window size exceeds w, we need to keep exactly w largest; we have to move smallest from selected to the other set if the new element is larger than some in selected.
So we can maintain:
- multiset "top" storing up to w largest d_i in current window (if window size <= w, then top contains all d_i).
- multiset "bottom" storing the remaining d_i.
We also maintain sum_top = sum of elements in top.
We also maintain sum_t = sum of t_i in window, sum_a = sum of a_i in window.
Then condition is: sum_t - sum_top <= k.
Now sliding window: for each left index l, we will have r as far as possible. Typically we use two pointers: increment r, update structures; while condition fails, increment l and remove its element, updating structures; keep track of max sum_a when condition holds.
But careful: The condition uses sum_top which depends on top w d_i. As we move l, we may need to remove an element from top or bottom. This can be done.
Time complexity: O(n log n) if we use balanced BST (like C++ multiset). In Python, we can use sorted list from bisect but removal is O(n) unless we use something like heap with lazy deletion or use two heaps. But we need both removal and insertion and ability to get min of top and max of bottom. We can use two heaps (max-heap for bottom? Actually we need to maintain top set as the largest w. We can use a min-heap for top (to get smallest in top) and a max-heap for bottom (to get largest in bottom). But with deletions of arbitrary elements (when sliding left), we would need lazy deletion. That's feasible: we can have two heaps and also counters for elements to be removed. But n up to 2e5, log n is fine. However, Python heaps are only min-heaps, so for bottom we need a max-heap by storing negative values. And we need to support removal of arbitrary values. We can use "lazy deletion" using dictionaries to track counts of elements that should be removed.
Alternatively, we can use "SortedList" from bisect? But that is not built-in, we could implement Fenwick tree or segment tree if values are limited. d_i = floor(t_i/2). t_i up to 1e4, so d_i up to 5000? Actually floor(t_i/2) <= 5000? t_i up to 1e4, floor(10000/2)=5000. So d_i are small (0 to 5000). That's important! d_i max 5000. And w up to n but we only need top w sum. Since d_i values are limited to a small range (0..5000), we could use a Fenwick tree (BIT) over frequencies to maintain counts and sums of d_i in the window, and then query the sum of the largest w d_i. That would be O(log M) per operation, where M=5000. That's very fast. For each add/remove, we update a BIT for frequency and BIT for sum. Then to compute sum of top w d_i, we can do a query: find the smallest value such that count of values >= that value is at least w? Actually we want the sum of the largest w values. Since d_i up to 5000, we can maintain an array freq[0..5000]. Then to get sum of largest w, we can iterate from 5000 downwards accumulating counts until we get w. But that would be O(5000) per operation, which could be 5000 * 2e5 = 1e9, too slow. However, we can use prefix sums via BIT to do binary search for the threshold where cumulative count from high end reaches w. Specifically, we can maintain a BIT that supports prefix sums over values (indexed by d). To get sum of top w, we can binary search on the BIT to find the smallest d0 such that count of d >= d0 is at most w? More precise: total count = cnt_total. We need the sum of the largest w elements. Let r = cnt_total - w (number of smallest elements to exclude). If we can get the sum of all elements and subtract sum of the smallest r elements. So we can get total sum of d in window (we can maintain sum_d_total easily by just adding/subtracting). Then we need sum of smallest r elements. If we can query the sum of the smallest r elements using BIT, we can compute sum_top = total_sum_d - sum_smallest_r. Because sum of largest w = total_sum - sum of smallest (cnt_total - w) if cnt_total >= w, else sum_all (if cnt_total < w). So we need to be able to compute the sum of the smallest r elements. We can maintain a BIT over frequencies and BIT over sums. To get sum of smallest r, we can perform a prefix query: find the largest index idx such that cumulative count <= r, and sum of those. But because there may be many elements with same value, we need to include part of that value. So we need to be able to get sum up to a certain rank. BIT can support prefix sums. So we can binary search on BIT for the rank. That's O(log M) per query. Good.
Thus we can maintain freq and sum BIT for d_i values. Then for each window, we can compute sum_top_d = if cnt_total <= w: sum_d_total; else: sum_d_total - sum_smallest(cnt_total - w). And we need to update freq and sum when adding/removing an element.
Then condition: sum_t - sum_top_d <= k. We maintain sum_t and sum_a as normal.
Sliding window approach: iterate over left from 0 to n-1, and maintain right pointer. Typically, we advance right as far as possible while condition holds. But careful: The condition uses sum_top_d which depends on the distribution of d_i. As we expand right, the window changes and sum_top_d may increase (if the new d_i is among the largest). So we need to recompute condition after each addition. So we can while r < n and condition after adding is satisfied, we add and update max sum_a. Then when condition fails, we break (or we could try moving left). But sliding window usually moves left when condition fails after adding, but we want to find maximal windows for each left. However, since we want max sum_a overall, we can use two pointers with while condition fails, we move left, and then continue expanding right. But careful: the condition is not monotonic with respect to r for fixed l? For a fixed l, as we increase r, sum_t increases, sum_d_total increases, and sum_top_d also increases but not necessarily monotonically? Actually sum_top_d = sum of largest w d_i in the window. Adding a new element d_new could increase sum_top_d if d_new is large enough to be among top w; else sum_top_d unchanged. So sum_t - sum_top_d generally increases as we add elements? sum_t always increases by t_new. sum_top_d either increases by d_new (if d_new is in top w) or stays same. If it stays same, then sum_t - sum_top_d increases by t_new. If it increases by d_new, then sum_t - sum_top_d increases by t_new - d_new = ceil(t_new/2) (since t_new - d_new = ceil(t_new/2) = partial cost). And since ceil(t_new/2) >= 1 (positive), it still increases. So sum_t - sum_top_d is non-decreasing as we expand right. So the condition becomes stricter as we increase r. So for fixed l, there is a maximal r such that condition holds, and beyond that it fails. This monotonic property allows two-pointer: we can move r forward, and when condition fails, we move l forward (which reduces sum_t and maybe sum_top_d) to try to satisfy again. Typically we maintain a window [l, r) and we attempt to extend r while condition holds; when fails, we increment l (and maybe r stays, because after removing left element, condition may become true again). Then we can continue.
But careful: Because we maintain top w d_i based on entire window, removing left element can affect sum_top_d. So we need to update structures correctly.
Thus algorithm:
Initialize l = 0, r = 0, sum_t = 0, sum_a = 0, BIT for d_i frequencies and sum_d. Also we need to know total count in window. Let's maintain cnt = 0.
For each iteration while r < n:
- Attempt to add element at r if condition after adding is <= k? Actually we can try to add and then check; if condition satisfied, we accept; else we need to move l first.
But typical two-pointer: while r < n:
Add element r: update sum_t += t_r, sum_a += a_r, update BIT with d_r (increase freq[d_r] and sum_d).
Then while condition sum_t - sum_top_d > k and l <= r:
remove element l: subtract sum_t, sum_a, update BIT (decrease freq[d_l] and sum_d).
l += 1
After removal, the window [l, r] is valid (or empty if l > r). Then we can update answer = max(answer, sum_a). Then r += 1.
But note: after adding element r, we might have made the window invalid. Then we remove from left until it's valid. The resulting window may not be maximal for given l, but that's okay; we track max sum_a. The two-pointer ensures we consider all valid windows because for each r we have the smallest l such that window [l, r] is valid, and we move l only forward. Since condition is monotonic with respect to inclusion, this works.
But is it monotonic? That is, if [l, r] is valid, then any subwindow with larger l (shrinking from left) is also valid? Actually if we remove an element, sum_t decreases and sum_top_d might decrease or stay same, so sum_t - sum_top_d might decrease or increase? Let's think: removing left element could either remove from top set if its d_i was among top w, or from bottom. If it was in top, sum_top_d decreases by d_l, and sum_t decreases by t_l, so change in sum_t - sum_top_d = -t_l + d_l = -(t_l - d_l) = -ceil(t_l/2) <= 0. So it decreases or stays same? Actually ceil(t_l/2) positive, so it decreases. If removed from bottom, sum_top_d unchanged, sum_t decreases by t_l, so sum_t - sum_top_d decreases by t_l (positive). So it definitely decreases. So validity condition becomes easier (more likely to be satisfied) after removing left element. So if [l, r] is invalid, we need to increase l (remove left) to make it valid. So the two-pointer works.
Thus we can implement sliding window with BIT to compute sum_top_d dynamically.
Now, we need BIT for d values. d_i = t_i // 2 (floor division). Since t_i up to 10000, d_i up to 5000. So we can set MAX_D = 5000. Actually t_i can be up to 10000, floor(t_i/2) max 5000, so d_i in [0,5000] inclusive. Also note t_i >= 2, so d_i >= 1? Actually t_i >= 2, so floor(t_i/2) >= 1. So d_i >= 1. But can be 0? If t_i=1? But t_i >=2, so min d = floor(2/2)=1. So d_i at least 1. But we can still handle 0 if needed.
We need two BITs: one for frequency counts, and one for sum of d values. Both size MAX_D+2 (maybe 5001). Or we can maintain total_sum_d easily by a variable; but we need sum of smallest r elements. We can use BIT for counts to find the threshold value. Actually to compute sum of smallest r elements, we can use a BIT over sums. Approach: Let total_cnt = cnt. If total_cnt <= w: sum_top_d = total_sum_d. Else let r = total_cnt - w (number of smallest to exclude). We need sum_smallest_r = sum of the r smallest d values in the window. To get that, we can binary search on BIT of counts to find the largest d value such that cumulative count <= r. That gives us a threshold value v where we have some count accumulated up to v. Suppose cumulative count up to v is cnt_v, which may be less than r. The remaining needed to reach r are from value v+1? Actually we need the sum of the smallest r elements. Let's define: We want the sum of the smallest r elements. Let's find the value x such that number of elements with d <= x is >= r, but number with d <= x-1 is < r. Then sum_smallest_r = sum_{d <= x-1} (cnt[d] * d) + (r - cnt_{x-1}) * x, where cnt_{x-1} is count of elements with d <= x-1. So we need to be able to get cumulative count and cumulative sum up to any value.
So we need BIT for count and BIT for sum. Both support prefix queries. Then we can binary search to find the smallest x such that prefix count >= r. Then sum_smallest_r = prefix_sum(x-1) + (r - prefix_count(x-1)) * x.
We can implement binary search on BIT using the typical method: find smallest index with prefix count >= r. Since BIT size small (5000), we could also just iterate from 0 to MAX_D to accumulate, but that would be O(5000) per check, which might be okay? 5000 * 2e5 = 1e9, too high. So need O(log M) per query.
Since M = 5000, log2(5000) ~ 13, so fine.
Now, we also need to update the BITs when adding/removing an element: add +1 to count[d] and +d to sum[d].
Now, we must be careful: d_i values up to 5000, but n up to 200k, so total operations O(n log M) ~ 200k * 13 = 2.6M, fine.
Thus sliding window can be implemented.
But wait: The sliding window approach with two pointers yields maximum sum of a_i for any subarray that is valid? Let's think: For each r, we find the minimal l such that [l, r] is valid, and compute sum_a for that window. Then we take maximum over all such windows. This covers all subarrays because any valid subarray [l, r] will be considered when r is at its right endpoint and l is the minimal left index for that r? Actually if we maintain for each r the smallest l such that window is valid, then the window [l, r] is valid, but there might be other valid windows with larger l (shorter) that we also consider? But we compute answer for each r after adjusting l, and the current window after removal is [l, r] which is valid. However, windows with larger l (i.e., shorter) also valid but will have sum_a <= sum_a of current window? Not necessarily; a shorter window may have higher sum_a if it contains larger a_i? But sum_a is cumulative; if we remove some a_i (which are positive because a_i >= 1?), a_i are positive (1 ≤ ai ≤ 10^4). So sum_a decreases when we remove elements. So the maximum sum for a given r would be achieved with the smallest l (largest window). But we need global maximum over all subarrays, not necessarily with smallest l for each r. However, if for a fixed r, the largest valid window starting at some l' yields the largest sum (since all a_i positive), yes, because adding more elements (with positive a) increases sum. So the maximal sum for given r is when l is as small as possible while still satisfying validity. So taking the window with minimal l for each r will give the maximum sum for that r. And then we take max over r. This yields the global maximum because any valid subarray [l, r] has sum_a <= the sum of the window from minimal_l(r) to r (since minimal_l(r) <= l, and all a_i positive). But careful: if a_i can be negative, it wouldn't hold, but here a_i are positive. Yes, all a_i >= 1, so sum_a is increasing with window length. So optimal window for a given right endpoint is the longest valid window (smallest l). So sliding window that maintains the smallest l for which [l, r] is valid will indeed capture the best for each r. And taking max over r yields global optimum.
Thus sliding window works.
But we must also consider the possibility that we may not use all w partials; condition uses sum_top_d which is sum of largest up to w d_i. That automatically accounts for using fewer if there are fewer elements. So it's fine.
Edge Cases: w could be larger than window length; then sum_top_d = total_sum_d. Condition becomes sum_t - total_sum_d <= k. But sum_t - total_sum_d = sum_i (t_i - d_i) = sum_i ceil(t_i/2). That's the total time if we partially listen to all songs in the window. That is indeed minimal possible time for that window (since we can partially listen to all songs, at most w limit but w >= L, so we can use partial for all). So condition is consistent.
Also, if window length L > w, we take sum of largest w d_i.
Now, what about the incomplete last song case? Could there be a scenario where it's beneficial to include a song but only listen to less than half, getting no pleasure, just to fill time? No, because that would waste time without gaining pleasure, so it can't improve total pleasure. So we ignore.
Thus the sliding window with BIT should work.
But we must also consider that we can start at any song x. The sliding window considers all contiguous subarrays, so it includes all possible starting points. Good.
Now verify with examples.
Example 1:
n=7, w=2, k=11
a: 3 4 3 5 1 4 6
t: 7 7 3 6 5 3 9
Compute d = floor(t/2): 3,3,1,3,2,1,4 (since 9//2=4)
Check optimal solution: start at song 2, partially listen to song 2 (ceil(7/2)=4 min, d=3), fully listen song 3 (t=3, d=1), partially listen song 4 (ceil(6/2)=3 min, d=3). Time = 4+3+3=10, pleasure = 4+3+5=12. So window [2,4] length 3, w=2, sum_t = 7+3+6=16, sum_d (largest 2) = d2=3, d4=3? Actually d2=3, d3=1, d4=3. Largest 2 are 3 and 3 sum=6. sum_t - sum_top_d =16-6=10 <=11. So valid. sum_a=4+3+5=12. Could we extend to song5? t5=5, d5=2, sum_t=21, sum_d sorted: 3,3,2,1 -> largest 2=3+3=6, sum_t - 6=15 >11, not valid. So window [2,4] is maximal.
Now sliding window should find this.
Check other possible windows: start at 1? Try [1,3]? t sum 7+7+3=17, d:3,3,1 largest2=6 -> 11, sum_a=3+4+3=10, time=11? Actually 17-6=11 <=11, so valid, pleasure=10. So max is 12.
Thus answer 12.
Example 2:
n=8, w=4, k=20
a:5 6 4 3 7 5 4 1
t:10 12 5 12 14 8 5 8
d = 5,6,2,6,7,4,2,4
Optimal answer 19 according to sample. Let's test: maybe window from 2 to 6? sum_t=12+5+12+14+8=51, top4 d? d:6,2,6,7,4 sorted:7,6,6,4 sum=23, sum_t-23=28>20. Not good. Maybe some combination. We'll trust sliding window later.
Example 3: n=1,w=1,k=5, a=6, t=9,d=4. sum_t=9, sum_top_d if w=1 => 4, time=5 <=5, sum_a=6. So answer 6.
Example 4: n=1,w=1,k=3, t=7,d=3, sum_t=7, sum_top_d=3, time=4>3, not valid. So answer 0 because cannot even partially listen? Actually partial listening would be ceil(7/2)=4 minutes, which exceeds k=3. So cannot listen to half; if we try to start the song and listen less than half, we get no pleasure. So answer 0. So our model yields no valid window since condition fails: sum_t - sum_top_d =7-3=4 >3, so window not valid. So answer 0, matches.
Thus approach seems correct.
Now need to implement BIT for counts and sums over d from 0 to MAX_D (5000). Since d_i can be up to 5000, but we should compute MAX_D = max floor(t_i/2) which is at most 5000, but we can set 5000 as safe.
Implementation details:
- Read n, w, k.
- arrays a[0..n-1], t[0..n-1].
- compute d[i] = t[i] // 2 (integer division).
- BIT class: size = max_d+2 (maybe 5005). Implement methods: add(idx, delta_count, delta_sum?) Or we maintain two BIT arrays: bit_cnt, bit_sum. Both 1-indexed. BIT operations: update(idx, val) adds val to the count and val*idx to sum? But careful: sum BIT should store sum of d values, not weighted by index. Since d is the value, we need to store the sum of d. So we need to update bit_sum at idx by d (the actual value). But we also need to query prefix sum of d up to idx. So we can have separate BITs: cnt BIT for frequencies, sum BIT for sums.
Thus:
- bit_cnt.add(idx, delta) where idx = d (or maybe d+1 for 1-indexing). We'll use index = d (since d from 0 to 5000) + 1 for 1-index.
- bit_sum.add(idx, delta * d) where d is the value.
But we have d variable; we can store d as value.
In add operation, we do:
bit_cnt.add(d_val, 1)
bit_sum.add(d_val, d_val)
Similarly for remove: add -1 and -d_val.
Now, to compute sum_top_d:
Let total_cnt = bit_cnt.query(MAX_D) (or we can keep a variable cnt_total for speed). But we need to use BIT to compute sum_smallest_r. So we can maintain cnt_total separately as we add/remove to avoid BIT query each time. But for correctness, we can also query BIT, but simpler to maintain an integer variable cnt_total.
We'll maintain:
cnt_total = number of elements in window
sum_d_total = sum of all d in window (we can maintain variable for sum_d_total as well, but we can also compute from BIT sum_all = bit_sum.query(MAX_D). But maintaining variable is easier and O(1).
Now:
if cnt_total <= w:
sum_top_d = sum_d_total
else:
r = cnt_total - w # number of smallest to exclude
# find smallest x such that prefix count >= r
# we need the sum of the smallest r elements
# Use binary search on BIT for counts to find x.
# let's define function find_kth(k) returns smallest index where cumulative count >= k.
# Since BIT supports prefix sums, we can binary search.
# Then sum_smallest = bit_sum.query(x-1) + (r - bit_cnt.query(x-1)) * x
# but careful: x is the value (d) where we have the r-th element. The value of x is the d-value.
# After we find x (the d value), we compute:
cnt_prev = bit_cnt.query(x-1)
sum_prev = bit_sum.query(x-1)
remaining = r - cnt_prev # number of elements with value x to take (at least 1)
sum_smallest = sum_prev + remaining * x
sum_top_d = sum_d_total - sum_smallest
However, note: d values may be large, up to 5000, BIT size maybe 5001. We'll use 1-indexed indices = d+1 to avoid 0? BIT typically uses 1-index. Let's set BIT indices from 1 to MAX_D+1 (since d can be 0). But d_i >= 1, but we can still handle 0. We'll set MAX_D = max_d (maybe 5000) and BIT size = MAX_D+2.
But we need mapping: value v -> index = v+1 (since v can be 0). Or we can just use index = v, but BIT requires index >=1. So use v+1.
So BIT size = max_d+2.
Now we need find_kth(k) to get the smallest index (in terms of value) where cumulative count >= k. Since our BIT is over indices that correspond to d values, we can perform binary search on BIT: start with idx = 0, then for step from highest power of two down to 0, check if idx+step <= size and bit_cnt.tree[idx+step] < k, then k -= bit_cnt.tree[idx+step], idx+=step. Actually typical BIT method to find smallest index with prefix sum >= k uses the tree built from frequencies. We can implement that. Since size is small (5000), we could also do a simple linear scan over values from 0 to MAX_D using a freq array and then accumulate; but that would be O(5000) per query, too slow (5000*200k = 1e9). So we need BIT with O(log MAX_D). But given MAX_D=5000, log2 5000 ~13, which is fine.
But note: BIT find_kth works when k is 1-indexed (the rank). We'll ensure k is between 1 and total_cnt.
Implementation of BIT:
class BIT:
def init(self, n):
self.n = n
self.tree = [0]*(n+1)
def add(self, idx, val):
while idx <= self.n:
self.tree[idx] += val
idx += idx & -idx
def sum(self, idx):
s = 0
while idx > 0:
s += self.tree[idx]
idx -= idx & -idx
return s
def find_kth(self, k):
# find smallest idx such that prefix sum >= k
idx = 0
bit_mask = 1 << (self.n.bit_length() - 1)
while bit_mask:
next_idx = idx + bit_mask
if next_idx <= self.n and self.tree[next_idx] < k:
k -= self.tree[next_idx]
idx = next_idx
bit_mask >>= 1
return idx + 1
But careful: This find_kth works if the tree stores frequencies and we want first index where cumulative sum >= original k. But we need to adjust because we might have values that are not exactly the sum? The typical implementation: start with idx=0, and for i from highest power of two down to 0, if idx+2^i <= n and tree[idx+2^i] < k, then k -= tree[idx+2^i], idx += 2^i. Then return idx+1. That works when tree is built as BIT. However, note that our BIT indices start at 1. So we need to set size = max_d+1? Actually we want indices from 1 to max_val+1 where max_val = max possible d (maybe 5000). We'll have max_val = 5000 (or compute actual max). We'll set BIT size = max_val+1 (since we map value v to index v+1, so max index = max_val+1). For BIT find_kth to work, we need the tree size to be a power of two? Not necessary, but the algorithm uses a mask that is the highest power of two <= n. So we can compute that.
We'll maintain separate BIT for counts only. For sum of d we can query using BIT_sum.
So algorithm:
Initialize:
max_d = max(t_i)//2 maybe up to 5000, but compute actual max_d from data to keep BIT small.
n, w, k = map(int, input().split())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
d = [ti // 2 for ti in t]
max_d = max(d) # <= 5000
BIT_cnt = BIT(max_d+2) # index = d+1, so max index = max_d+1, we need size at least max_d+1
BIT_sum = BIT(max_d+2)
Define function add(i):
nonlocal sum_t, sum_a, sum_d_total, cnt_total
sum_t += t[i]
sum_a += a[i]
d_val = d[i]
sum_d_total += d_val
cnt_total += 1
idx = d_val + 1
BIT_cnt.add(idx, 1)
BIT_sum.add(idx, d_val)
Define remove(i):
subtract similarly.
Define get_sum_top():
if cnt_total <= w:
return sum_d_total
else:
r = cnt_total - w # number of smallest to exclude
# find index (value) where cumulative count >= r
# using BIT_cnt.find_kth(r)
idx = BIT_cnt.find_kth(r) # returns the BIT index where prefix sum >= r. This index corresponds to d = idx-1.
d_thresh = idx - 1
# Now compute sum of smallest r elements
# sum of all d < d_thresh
cnt_below = BIT_cnt.sum(idx-1) # prefix sum up to index-1, which corresponds to values < d_thresh
sum_below = BIT_sum.sum(idx-1)
# remaining needed from d_thresh: take (r - cnt_below) elements of value d_thresh
# but we need to ensure that we have enough elements of that value. Since idx is the first index where cumulative count >= r, it means that cnt_below < r and cnt_below + freq[d_thresh] >= r.
# So remaining = r - cnt_below
sum_smallest = sum_below + (r - cnt_below) * d_thresh
return sum_d_total - sum_smallest
But careful: The BIT find_kth returns the index in BIT (1-indexed) such that prefix sum up to that index >= r. The value we need is d = idx-1. For sum_below, we query up to idx-1 (values < d_thresh). That's correct.
Edge case: If r = 0 (i.e., cnt_total == w), then sum_top_d = sum_d_total. Our if condition handles cnt_total <= w, so r >0 only when cnt_total > w.
Now compute current_time = sum_t - sum_top_d. Check if <= k.
Now sliding window:
l = 0
sum_t = 0
sum_a = 0
sum_d_total = 0
cnt_total = 0
ans = 0
for r in range(n):
add(r)
# while current_time > k and l <= r:
while True: