You have a playlist consisting of n songs. The i-th song is characterized by two numbers t_i and b_i — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of 3 songs having lengths [5, 7, 4] and beauty values [11, 14, 6] is equal to (5 + 7 + 4) ⋅ 6 = 96.
You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3 ⋅ 10^5) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next n lines contains two integers t_i and b_i (1 ≤ t_i, b_i ≤ 10^6) — the length and beauty of i-th song.
Output
Print one integer — the maximum pleasure you can get.
Examples
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
Note
In the first test case we can choose songs {1, 3, 4}, so the total pleasure is (4 + 3 + 6) ⋅ 6 = 78.
In the second test case we can choose song 3. The total pleasure will be equal to 100 ⋅ 100 = 10000.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to solve: given n up to 3e5, choose at most k songs to maximize (sum of t_i) * min(b_i) over chosen set.
This is a classic problem: maximize product of sum of lengths times minimum beauty. Usually we sort songs by beauty descending, then maintain a data structure for top (k-1) lengths? Actually typical solution: sort by beauty descending, then iterate over songs as potential minimum beauty (the chosen set's minimum beauty will be the beauty of the song with smallest beauty among chosen). Since we want maximize sum(t)*min(b), we consider each song as candidate for the minimum beauty. If we sort by beauty descending, then when we process song i, its beauty is the current minimum if we include it and only include songs with beauty >= its beauty. To maximize, we would like to take among songs with beauty >= current song's beauty, up to k songs (including current) that maximize sum of lengths. However we can also take fewer than k, but since sum is multiplied by min beauty, adding a song with positive length always increases sum, but could it decrease min? No, because we only consider songs with beauty >= current min, so min remains current song's beauty. So we should always take as many songs as possible? Actually, we can take at most k songs. So we want to choose up to k songs from the set of songs with beauty >= current beauty, such that the sum of lengths is maximized. Since all lengths are positive, we would like to take the k songs with the largest lengths from that set (if we include the current song, but current song must be included because it's the minimum beauty; but what if we take a set where the minimum beauty is larger than current song? Then it would be considered later when processing higher beauty. So for each candidate, we assume current song is the minimum beauty, so we must include it. Then we can choose at most k-1 other songs from those with beauty >= current beauty (i.e., from songs already processed in descending order) that have the largest lengths. So we need to maintain a data structure to keep track of top (k-1) lengths among seen songs (excluding current? Actually including current, we need at most k songs total. So we can consider that we need to compute sum of top up to (k-1) lengths from previously processed songs (i.e., those with higher beauty) plus current song's length. However careful: The current song itself may not be among the top lengths; but we must include it. So total sum = t_i + sum of largest (k-1) lengths among songs with beauty > b_i (or >=, but including those with same beauty? Since we sorted descending, when processing a song with beauty b, all previous songs have beauty >= b? Actually if we sort by beauty descending, and we process in that order, then when we are at song i, all earlier songs have beauty >= b_i. But careful: There may be songs with equal beauty; the ordering among them is arbitrary. If we treat "minimum beauty" as b_i, then we can include songs with beauty equal to b_i, but if we include them, the minimum remains b_i. So we can also include songs with equal beauty. However in the sorted order, if we process i, some songs with equal beauty may be after i (if we break ties arbitrarily). To ensure we consider all songs with beauty >= b_i, we could process in decreasing beauty and as we go, add songs to a data structure, then for each song we consider it as the minimum, but we must include it. Since it is currently the last among those with that beauty if we process in strictly descending order? Actually we can adopt the approach: sort songs by beauty descending. Then iterate over sorted list. Maintain a min-heap (or multiset) of at most k largest lengths among the songs seen so far? However we must include the current song. But if we only keep top k-1 lengths among previous songs, we can compute sum = t_i + sum(top (k-1) lengths among previous songs). However what if there are fewer than k-1 previous songs? Then we just sum all previous lengths. That yields a candidate pleasure = (t_i + sum_{top up to k-1}) * b_i. But is that always valid? It assumes that we can include any of the previous songs, which have beauty >= b_i because they are sorted descending. So yes, those songs have beauty at least b_i. So the set consisting of current song and the top (k-1) lengths from previous songs (i.e., with higher or equal beauty) will have min beauty = b_i (since current has the lowest beauty among them if we consider previous songs may have equal beauty; but if some previous songs have equal beauty, then min is still b_i). So it's valid.
But is there a case where we might want to include fewer than k songs even when more are available? Since all lengths are positive, adding a song always increases sum, and min beauty unchanged, so it increases product. So we should always take as many as possible up to k. So indeed for each i, the optimal set with min beauty exactly b_i (and including i) is to take i and the (k-1) songs with highest t among those with beauty >= b_i (excluding i). However we must ensure that i is included; but it could be that i is not among the top k lengths among those with beauty >= b_i. The set of k songs that maximizes sum of lengths among songs with beauty >= b_i might not include i. That set would have min beauty >= b_i, potentially higher, and would be considered when its minimum (which is the smallest beauty in that set) is some other song. But if we force min beauty = b_i, we must include at least one song with beauty exactly b_i (the minimum). i is a candidate. Could the optimal set with min beauty exactly b_i be different, i.e., include some other song with beauty b_i as the minimum, not necessarily i? That's fine; we will consider that other song when it is processed. So our approach of iterating over each song as potential minimum is correct: for each song i, compute best set where i is the minimum (i.e., all other chosen songs have beauty >= b_i, and i is the one with smallest beauty). The optimal overall will be max over i.
Now the algorithm: Sort by b descending. Maintain a data structure that can give the sum of the largest up to (k-1) lengths among the songs processed so far (i.e., those with beauty >= current b_i). Then for each song i, we compute candidate = (t_i + sum_of_top_min(k-1, previous_songs_lengths)) * b_i. But careful: The "previous songs" are those we have already added to the data structure before processing i? In typical solution, we iterate i from 0 to n-1, and at each step we compute candidate using current data structure (which contains previously processed songs, i.e., with beauty >= b_i). Then we add current song's t to the data structure for future iterations. This works because when processing i, we consider it as minimum; the other songs must have beauty >= b_i, which are exactly the songs processed earlier (since we sorted descending). Those earlier songs have beauty >= b_i. If there are ties, some songs with same beauty may not have been processed yet. But we can handle ties by either processing in descending order and adding current song after computing candidate. That ensures that when considering i as minimum, we only include songs with strictly greater beauty (or equal if they come earlier). However if there are multiple songs with same beauty, the minimum could be any of them. If we process in some order, for a given b, the first song with that beauty will have no other songs with same beauty in the data structure yet. That may produce a candidate that does not consider taking other songs with same beauty as well (i.e., the set where min = b, but includes other songs with same beauty). But that set would be considered when we process the last of those equal-beauty songs as the minimum, because when we get to that last song, all others with equal beauty will be in the data structure (since they were added earlier if we process in some order). So as long as we process ties in some order and compute candidate after adding? Actually typical solution: sort by b descending, then for each song in order, compute answer as (t_i + sum of largest (k-1) lengths from a min-heap that stores at most k-1 lengths? Actually common solution is: Use a min-heap to keep the k largest lengths among seen songs. The sum of lengths in heap is sum of top k? Let's derive.
Alternative approach: For each song, we consider it as the minimum beauty; we need the sum of lengths of up to k-1 songs with higher beauty (or equal). But we need to be careful with ties: if we add current after computing, then for equal beauty songs, they are not considered as "higher beauty" but they are allowed because they are not less. However the set where min beauty = b should allow including other songs with beauty = b, but they are not in the data structure yet if we process in order. But when we process the last of those equal-beauty songs, the earlier ones have been added, so that set can be captured (with the last as the minimum). So overall maximum will be captured.
But is it possible that the optimal set with min beauty = b includes a particular song i as the minimum, but there is another song j with same beauty that is also in the set? That's fine; when i is processed, j may not yet be in the data structure; so the candidate computed for i may miss j. However the candidate using i as minimum that includes j would have min beauty still b, but if we choose i as the minimum and include j, the min is still b. But if j is not in data structure when processing i, we can't capture that. But that same set could be considered when we process j as the minimum (if j is the smallest among them? Actually both have same b, so any of them could be considered the minimum; the set's min beauty is b, and any song with beauty b in the set can be considered the "representative" minimum. So if we process j later, and include i (which is already added to data structure because i was processed earlier), then that set will be captured. So overall max will be found. So it's fine to compute candidate before adding current song to data structure.
Thus algorithm:
Sort songs by b descending.
Maintain a min-heap (priority queue) that holds the lengths of up to k-1 songs from the previously processed songs. Actually we need to quickly get sum of the largest up to (k-1) lengths among previous songs. We can maintain a min-heap of size at most (k-1) that stores the largest (k-1) lengths encountered so far. The heap is a min-heap, so the smallest among the top (k-1) is at the top. When we have a new length from a previous song, if heap size < (k-1), we push it and add to sum. If heap size == (k-1), we compare with the smallest in the heap; if the new length > that smallest, we pop the smallest, subtract it from sum, push the new length, add to sum. This way sum always holds the sum of the current largest up to (k-1) lengths among all seen songs.
Iterate through sorted list. For each song i:
Let candidate = (t_i + sum) * b_i. (Note: if k==1, then we have no other songs allowed; sum should be 0. So we initialize heap empty, sum=0.)
Update answer = max(answer, candidate).
Then add t_i to the data structure for future iterations: treat it as a candidate for top lengths for later songs. But careful: when k>1, we allow up to k-1 other songs, so we add to the heap with capacity k-1. But note: The current song will be added to the heap after we use it as minimum; for later songs (with lower beauty), they can include this song as one of the "higher beauty" songs. So yes, we add it.
Edge cases: If k == 1, we just need max(t_i * b_i) because we can choose at most 1 song. Our algorithm: sum=0 always, candidate = t_i * b_i, then we add t_i to heap? But heap capacity is k-1 = 0, so we should not add any. So we skip addition. That works.
Time complexity: O(n log k) which is fine for n up to 3e5.
We need to be careful about integer sizes: t_i, b_i up to 1e6, k up to 3e5, sum of lengths up to 3e5 * 1e6 = 3e11, multiplied by b up to 1e6 gives up to 3e17, which fits in 64-bit signed (max ~9e18). So we can use long long (int64).
Implementation steps:
Read n, k.
Create vector of pairs (b, t) or (t, b). We'll sort by b descending. Better store as (b, t).
Sort by b descending.
Initialize a min-heap (priority_queue<int, vector, greater>) for lengths, but we need to limit to size = k-1.
long long sum = 0, ans = 0.
For each song in sorted order:
long long cur = (t_i + sum) * b_i;
ans = max(ans, cur);
Then add t_i to the heap if k > 1:
if (heap.size() < k-1) {
heap.push(t_i);
sum += t_i;
} else {
if (k-1 > 0) { // always true if heap size == k-1? Actually if k==1 then we skip.
if (heap.top() < t_i) {
sum -= heap.top();
heap.pop();
heap.push(t_i);
sum += t_i;
}
}
}
Print ans.
But we need to consider that we might also consider sets of size less than k where the sum is from fewer songs but that could yield higher product? Since all lengths positive, adding more songs increases sum, so for a fixed min beauty, we always want as many songs as possible. But could it be that taking fewer than k songs yields a higher product because the min beauty might increase? Actually min beauty is determined by the song with smallest beauty in the set. If we take fewer songs, we could possibly drop a song with low beauty, thereby increasing min beauty. That's captured by considering different candidates for min beauty. For a given candidate minimum, we are taking the maximum possible sum from songs with beauty >= that min beauty, up to k songs. So it's optimal.
But there's nuance: Suppose we have a scenario where taking exactly k songs includes a song with very low t, but we could take fewer songs with higher total sum? Actually taking fewer songs can't have higher total sum because we drop some positive t. So sum always non-decreasing as we add songs. So for fixed min beauty, sum is maximized by taking as many songs as possible from the allowed pool, i.e., up to k. However, there is a twist: we must include at least one song with beauty equal to the min. So if we consider a particular min beauty candidate i, we must include it. Among other songs, we choose the ones with highest t to maximize sum, limited to k-1. That's what we do.
But is it always optimal to take exactly k songs? If the number of songs with beauty >= b_i is less than k, then we take all of them, which is fewer than k, but that's still maximal for that min beauty. Our algorithm using sum of top (k-1) among previous songs will take up to k-1, but if there are fewer than k-1 previous songs, heap size will be less and sum will be sum of all previous. That works. So we don't need special handling.
Potential issue: When k=1, heap size = 0, we skip addition; candidate = t_i * b_i, correct.
But what about the case where we might want to choose a set where the minimum beauty is from a song that is not among the top k lengths? That's fine; we include it anyway.
Thus algorithm seems correct.
Let's test on given examples.
Example 1:
n=4,k=3
songs:
4 7, 15 1, 3 6, 6 8
Sort by b descending: b:8,t:6; b:7,t:4; b:6,t:3; b:1,t:15.
k-1=2.
Initialize sum=0, heap empty.
i1: b=8,t=6: candidate=(6+0)*8=48. ans=48. Add t=6 to heap: size<2 so push, sum=6.
i2: b=7,t=4: candidate=(4+6)*7=70. ans=70. Add t=4: heap size=1 (<2) push, sum=10.
i3: b=6,t=3: candidate=(3+10)*6=78. ans=78. Add t=3: heap size=2 (now =2), but capacity is 2, so we need to check if t=3 > heap.top()? Heap currently has 6 and 4, min=4? Actually min-heap: top is smallest: 4. Since 3 < 4, we do not push, heap unchanged. sum stays 10.
i4: b=1,t=15: candidate=(15+10)*1=25. ans remains 78. Add t=15: heap size=2, heap.top=4, 15>4, so pop 4 (sum-=4->6), push 15, sum+=15->21. But not needed. final ans=78. matches.
Example 2:
n=5,k=3
songs:
12 31, 112 4, 100 100, 13 55, 55 50
Sort by b descending:
b:100,t:100
b:55,t:13? Wait second: song 4: 13 55 -> b=55,t=13
song 5: 55 50 -> b=50? Actually 55 50: t=55, b=50.
song 1: 12 31: b=31, t=12
song 2: 112 4: b=4, t=112.
But also there is song: maybe we have: (12,31) -> t=12,b=31; (112,4)-> t=112,b=4; (100,100) -> t=100,b=100; (13,55)-> t=13,b=55; (55,50)-> t=55,b=50.
Sorted descending b: 100 (t=100), 55 (t=13), 50 (t=55), 31 (t=12), 4 (t=112). k-1=2.
Initialize sum=0, heap empty.
i1: b=100,t=100: candidate=(100+0)*100=10000, ans=10000. Add t=100: heap size<2 push, sum=100.
i2: b=55,t=13: candidate=(13+100)55 = 11355=6215. ans stays 10000. Add t=13: heap size=1<2 push, sum=113.
i3: b=50,t=55: candidate=(55+113)50 = 16850=8400. ans 10000. Add t=55: heap size=2 (now exactly 2?) Actually heap currently has 100 and 13? Wait we have pushed 100 and 13, so size=2, capacity 2. Now t=55 > heap.top()? heap min is 13, so pop 13, sum-=13 ->100, push 55, sum+=55 ->155. So heap now contains 100 and 55.
i4: b=31,t=12: candidate=(12+155)31 = 16731=5177. Add t=12: heap top=55? Actually min is 55? heap has 55 and 100, min=55, 12 < 55 so no push.
i5: b=4,t=112: candidate=(112+155)4=2674=1068. ans=10000. Add t=112: heap size=2, top=55, 112>55, pop 55, sum-=55 ->100, push112, sum+=112 ->212. final ans=10000. matches.
So algorithm works on examples.
But is there any scenario where we might need to consider sets of size less than k but not because there aren't enough songs, but because adding a song with positive length could reduce the min beauty? However our candidate ensures min beauty is fixed to current song's b, and we only add songs with beauty >= b. So adding songs doesn't reduce min beauty. So it's always beneficial to add songs as long as we don't exceed k. So the maximum sum for that min beauty is indeed to take up to k songs with the largest lengths (including the minimum song). However careful: the minimum song itself might have a small length; we are forced to include it, but if we had the option to choose a different minimum with same beauty, we might get a larger sum. That's covered by iterating all.
Thus solution is correct.
Now implement:
Input reading: use scanf or fast IO.
Use vector<pair<int, int>> songs; store (b, t) or (t, b). Since we need to sort by b descending, easier to store (b, t). Then after sorting we iterate.
Use priority_queue<int, vector, greater> pq; // min-heap
long long sum = 0;
long long ans = 0;
int cap = k - 1;
for i = 0..n-1:
b = songs[i].first, t = songs[i].second;
cur = (sum + t) * b;
if cur > ans: ans = cur
if cap > 0:
if pq.size() < cap:
pq.push(t);
sum += t;
else:
// pq.size() == cap
if (cap > 0 && t > pq.top()):
sum -= pq.top(); pq.pop();
pq.push(t);
sum += t;
print ans.
But what about if k == 0? k is at least 1 per constraints.
Edge: When k=1, cap=0, we never add to heap, sum remains 0. candidate = t * b, correct.
Time O(n log k) ~ O(n log n) but k <= n, okay.
But we need to consider that we are using t_i up to 1e6, but sum may exceed 2^31, use long long.
Now, check potential pitfalls: The sorting by b descending, but we must handle large n.
Now, is there any more efficient way? This is fine.
But wait, there's another nuance: The problem statement: "You need to choose at most k songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible." So we can choose fewer than k. Our algorithm considers for each i the set of up to k songs that includes i and chooses the largest t from others. Since we always take up to k, but if there are fewer than k eligible songs, we take fewer. So we are covering the "at most k" condition.
Now, but what about a set that does not include any specific song as the minimum? Actually every non-empty set has a minimum beauty. So it's covered.
Now, is it possible that the optimal set has size less than k but our algorithm for a given i may take k songs? That's fine because if taking k songs gives larger product than taking fewer, it's better. If taking fewer gives larger product, it's because the minimum beauty is higher. That case will be captured when we consider a higher minimum beauty (i.e., later in sorted order? Actually earlier since descending). For example, suppose we have two songs: one with high beauty and low length, another with low beauty and huge length. For k=2, maybe taking only the high beauty song yields product = t1*b1, while taking both yields (t1+t2)min(b1,b2) which could be smaller. That's captured because when we consider the song with high beauty (b1) as minimum, we will also consider adding the other song (if its beauty >= b1? If the other song has lower beauty, it wouldn't be allowed because it would reduce min below b1. So when processing the high beauty song, we cannot include the low beauty song. So the candidate for high beauty song is just t1b1 (since cap=1, but we can only include songs with beauty >= b1; the low beauty song does not qualify). Then when processing the low beauty song as minimum, we include both, compute (t1+t2)*b2. We compare both and take max. So indeed the algorithm handles that.
Now, what if there are multiple songs with same beauty and we want to take a set of size less than k but still include more than one of them? That's captured when we process the last of them (the one with that beauty that is processed last) as the minimum, because earlier ones are in heap and can be included. So it's fine.
Thus algorithm stands.
But there's an alternative approach: sort by beauty descending, maintain a min-heap of size k that holds the lengths of the current set, and sum of heap. As we iterate, we add t_i to heap (maintaining size k by popping smallest if exceeds k). Then candidate = sum * b_i. But does that work? Let's analyze: If we maintain a heap of size exactly k (or at most k) containing the k largest lengths among processed songs (including current)? But then sum is sum of k largest lengths among songs with beauty >= current b_i? But we haven't forced inclusion of a song with beauty exactly b_i. For a given i, if we consider the set of up to k songs from those with beauty >= b_i, the maximum sum would be the sum of the k largest lengths among them. However, the minimum beauty of that set would be the minimum beauty among those k songs, which could be > b_i, because we might have chosen k songs all with beauty > b_i. That set would correspond to a min beauty that is the smallest among those k, which might be some song j (with beauty >= b_i). So if we compute sum_of_top_k * b_i, that might overestimate because the actual min beauty of that set would be at least b_i, but could be higher. However, if we take the sum of top k lengths among songs with beauty >= b_i, the product (sum) * (minimum beauty of that set) is at most (sum) * b_i? Actually min beauty >= b_i, so product could be larger or equal to sum * b_i. But we are computing sum * b_i, which is a lower bound for that set's actual product if min beauty > b_i. But we want to compute the maximum product exactly, not an underestimate. But if we use sum * b_i as candidate, we might miss a set where min beauty > b_i but we didn't compute its product because we used a smaller b_i. However, that set will be considered when we process the actual minimum beauty song among that set. For example, suppose we have songs with beauty 10, t=100 and beauty 9, t=1. For k=2, sorted descending: b=10,t=100; b=9,t=1. When processing first song (b=10), we have heap of top k lengths? If we maintain a heap of size k that always contains the current song and previous? Let's test alternative: Many solutions to a similar problem "Maximum pleasure" or "Maximum value of (sum of lengths) * (minimum beauty)" use exactly the method we described (candidate before adding). But I've also seen a variant: sort by beauty descending, maintain a min-heap of size k that stores lengths; at each step, add t_i, if heap size > k, pop smallest; then answer = max(answer, sum * b_i). Let's test this variant: For the example above: n=2,k=2. Sorted: (10,100), (9,1). Start sum=0, heap empty. Process first: add t=100, heap size=1 (<=k), sum=100. candidate = 100 * 10 = 1000. Then process second: add t=1, heap size=2, sum=101. candidate = 101 * 9 = 909. Max=1000. But actual optimal: Choose both: (100+1)9=909, choose only first: 10010=1000, so max=1000. That works. But consider scenario where best is both: Example 1: (b=8,t=6), (7,4), (6,3), (1,15), k=3. Sorted: 8,6; 7,4; 6,3; 1,15. Using heap of size k: Process 8: add 6 -> sum=6, heap size=1, candidate=68=48. Process 7: add 4 -> heap size=2, sum=10, candidate=107=70. Process 6: add 3 -> heap size=3, sum=13, candidate=13*6=78. Process 1: add 15 -> heap size would become 4 >3, so pop smallest? min-heap: currently contains 6,4,3? Actually the heap is min-heap, we push lengths; after processing first three, we have lengths 6,4,3 (maybe order). Sum=13. Then adding 15: push 15, size=4, pop smallest (3), sum = 13+15-3 =25, heap now contains 6,4,15. candidate = 25 * 1 = 25. Max=78. That's correct. So this alternative method also yields correct answer in these examples. Let's analyze why it works: For each song i in sorted order (by decreasing b), we maintain a multiset (heap) of the lengths of up to k songs with the largest lengths among all songs processed so far (i.e., among those with beauty >= current b_i). Actually, we always keep exactly the largest k lengths among processed songs? Not exactly; we maintain a heap that stores the lengths of the songs we have processed, but we limit its size to k. This is effectively keeping the k largest lengths among processed songs because we always pop the smallest when size exceeds k. So at step i, the heap contains the k largest lengths among songs [0..i] (including current). The sum is the sum of those k (or fewer if less than k). Now, the candidate we compute is sum * b_i. But what does this represent? It represents the product of the sum of the top k lengths among songs with beauty >= b_i (including possibly some with beauty = b_i) times b_i. However, the actual set of those k songs might have a minimum beauty that is > b_i. If so, then the product for that actual set would be sum * (actual min) which is >= sum * b_i. So sum * b_i is a lower bound for the product of that set. But we are taking max over i, and the actual optimal set's minimum beauty, say b_min, when we process the song with that beauty (or when we process the song that is the minimum), the heap will contain the top k lengths among all songs with beauty >= b_min. The actual set that achieves optimum might be exactly those k songs (or fewer), but its product is sum_actual * b_min. When we compute candidate at the step where b_i = b_min, we compute sum * b_min, where sum is the sum of top k lengths among songs with beauty >= b_min. But is it guaranteed that the sum of the actual optimal set equals that sum? Possibly the optimal set might not consist of the top k lengths, because we must include at least one song with beauty exactly b_min, and the set of top k lengths among all songs with beauty >= b_min might exclude that b_min song if its length is small. However, note that the product of the set of top k lengths (which may not include the minimum beauty song) would have min beauty > b_min, so its product would be higher if sum is similar, but might not be achievable because that set might have min beauty > b_min, so its product is sum * (greater min). But could that set have a larger product than the optimal set we are looking for? Possibly, but that set would be considered when processing the actual minimum of that set, which is higher than b_min. So the maximum over all i of sum_i * b_i might still capture the optimum. But we need to verify that our candidate for b_i (where b_i is the current song's beauty) actually corresponds to a valid set where the minimum beauty is exactly b_i. Because if the heap contains k songs all with beauty > b_i, then the set represented by the heap does not have min beauty b_i; its min beauty is the smallest beauty among those k songs, which is > b_i. However, we are not enforcing that the set includes the current song. So the candidate sum * b_i is not necessarily the product of any valid set (since the set of songs we are summing might have a higher min beauty). But we are taking the product of sum (of those k songs) times b_i, which is less than or equal to the actual product of that set. So we might be underestimating the product of that set. However, we might be overestimating? Actually if the heap set's min beauty is > b_i, then the real product is sum * min_beauty > sum * b_i. So our candidate is smaller than the real product. That's safe in terms of not overestimating beyond actual feasible product? Wait, we want to compute the maximum feasible product. If we compute candidate = sum * b_i, and the actual feasible product for the set of those k songs is higher, then candidate is not the true product of that set, but we might miss the true product because we never compute sum * min_beauty for that set. However, we will compute the true product when we consider b_i equal to the actual min beauty of that set. At that time, the heap will contain (maybe) those same k songs, and we will compute sum * that b (actual min). So the maximum over i will include the actual product. So using sum * b_i for each i is safe because we will eventually compute the actual product at the step where b_i equals the min beauty of the optimal set. But could candidate = sum * b_i ever be larger than any feasible product? That would be a problem. But is it possible? Suppose we have k songs with lengths L1,...,Lk and min beauty M, we compute sum(L) * b_i for some b_i less than M. Since b_i < M, sum(L) * b_i < sum(L) * M, so it's less than the product of that set. So it cannot exceed the product of that set. However, it could exceed the product of some other set? But we compare to the maximum feasible product. If we pick b_i such that the heap's min beauty is > b_i, then candidate is less than the product of that heap set. So the maximum of candidate over i will be at most the maximum feasible product? Not necessarily: Could there be a b_i for which the heap sum is large and b_i is also large, but the heap's min beauty is exactly b_i? That's when the current song is among the heap? But if we add the current song before computing candidate, then the heap includes current song. However, the heap may have popped some song with small length but maybe that song had the minimum beauty? Let's analyze the alternative method more carefully.
The alternative method that many people use: Sort by beauty descending. Initialize empty min-heap and sum=0. For each song in sorted order:
Add its length to heap and sum.
If heap size > k: pop smallest length from heap, subtract from sum.
Then ans = max(ans, sum * beauty_i).
This method works and is often used for similar problems (like "Choosing flowers" or "Maximum value of (sum of some attribute) * min(attribute)"). Let's reason about its correctness.
At iteration i (0-indexed), we have processed songs 0..i sorted by decreasing beauty. We maintain a multiset (heap) of the lengths of at most k songs from these processed songs, specifically the k songs with the largest lengths among them (since we pop smallest when exceed k). So the heap contains the k largest lengths among processed songs (or fewer if less than k). Let S_i = sum of lengths in heap. Then we compute candidate = S_i * b_i. The idea: Consider the set consisting of the songs that contributed to the heap at this point (i.e., the current k largest lengths). However, note that the heap might not contain exactly the songs that have the k largest lengths among all processed songs? Actually by construction, it does: we add each song's length, and if heap size > k, we remove the smallest. So after processing each song, the heap contains the k largest lengths among all songs processed so far (if there are at least k). Yes, that's a classic way to maintain top k elements.
Now, what does candidate represent? The set of songs that are currently in the heap has a minimum beauty that is at least b_i (since all processed songs have beauty >= b_i). Actually, all processed songs have beauty >= b_i because we sorted descending. So the minimum beauty among the heap songs is some b_min_heap >= b_i. The product for that set would be S_i * b_min_heap, which is >= S_i * b_i. So candidate S_i * b_i is a lower bound on the product of that set.
But why would taking the product with b_i give the maximum possible pleasure? The intuition: For any set of at most k songs, let its minimum beauty be b_min. When we consider the step where the current beauty is b_min (i.e., when we process the song with beauty b_min in the sorted order), all songs in that set have beauty >= b_min, so they have been processed (including the one with beauty b_min). Moreover, the heap at that step contains the k largest lengths among all processed songs. Since the set is a subset of processed songs of size <= k, the sum of its lengths is <= sum of the k largest lengths among processed songs, i.e., <= S_i. Therefore, the pleasure of that set is (sum_set) * b_min <= S_i * b_min. But we don't have S_i * b_min, we have S_i * b_i where b_i = b_min? Actually at that step, b_i = b_min (the current song's beauty, which is the minimum of the set if we are processing the song that is the minimum). But careful: In the sorted order, there might be multiple songs with the same beauty b_min. The set's minimum is b_min, but the specific song that is the minimum might not be the one we are processing at that exact iteration if we process another song with the same beauty. However, because we process all songs with that beauty, at some iteration where the current beauty is b_min, the heap will have included all songs with beauty >= b_min, i.e., all songs in the set, and also possibly others. But the key is: For the iteration where b_i = b_min, we have S_i >= sum_set, so S_i * b_min >= sum_set * b_min. Therefore, the candidate S_i * b_min is an upper bound on the pleasure of that set? Actually we have S_i * b_min >= sum_set * b_min, so candidate is at least as large as the set's pleasure. That's a problem: The candidate could be larger than the actual pleasure of any valid set, because S_i might include songs that are not in the set, but those extra songs might have beauty > b_min, so including them would increase sum but not decrease min (if they are all >= b_min). However, if we include extra songs, the set size might exceed k, but we limit heap to at most k songs, so S_i corresponds to sum of k songs (or fewer). Could those k songs all have beauty >= b_min? Yes. So the set of those k songs is a valid set (since size <= k). Its pleasure would be S_i * (minimum beauty among those k songs). But that minimum beauty might be > b_min. So the actual pleasure of the heap set is S_i * b_min_heap, which is >= S_i * b_min (since b_min_heap >= b_min). So S_i * b_min is a lower bound on the pleasure of the heap set, not an upper bound. But the heap set itself is a valid set, so its actual pleasure (S_i * b_min_heap) could be higher than S_i * b_min. However, we are computing S_i * b_min, which might be less than the actual pleasure of that heap set. But we are taking max over i, so we might miss the actual pleasure if we only compute lower bound. But we will also compute S_i * b_min_heap when we process the song with beauty = b_min_heap? Let's examine: The heap set's minimum beauty is the smallest beauty among the songs currently in the heap. Suppose that minimum is b* > b_i. When we later (or earlier?) process the song with beauty b*, the heap at that time may contain a different set of songs, not necessarily the same as now. So the candidate S_i * b_i might not capture the pleasure of the heap set. However, note that the heap set is a valid set of at most k songs. Its pleasure is sum_of_those_k_lengths * b*. Since b* > b_i, its pleasure is larger than S_i * b_i. To capture that, we need to consider the iteration where the current beauty is b*. At that iteration, the heap will contain the k largest lengths among songs with beauty >= b*. Since b* is the minimum of the heap set, all songs in that heap set have beauty >= b*, so they are included in processed songs by that iteration. Moreover, since we maintain the k largest lengths, the sum S at that iteration will be at least the sum of lengths of the heap set (because that set is a candidate of size <= k among songs with beauty >= b*). Actually, the heap at iteration for beauty b* will contain the k largest lengths among all songs with beauty >= b*. Since the heap set we are considering is a particular set of size <= k with all beauty >= b*, its total length is ≤ the sum of the k largest lengths among those songs. So S_j (at b*) >= sum_heap_set. Therefore, S_j * b* >= sum_heap_set * b*. So the candidate at that iteration is S_j * b*, which is >= the pleasure of the heap set. But we don't know if equality holds; it could be strictly greater if S_j includes different songs with larger total length but still minimum beauty b*? That's possible. Then S_j * b* would correspond to a possibly better set. So the max over i of S_i * b_i will be at least as large as the pleasure of any valid set? Let's try to prove: For any valid set T (size <= k), let b_min = min_{j in T} b_j. Consider the iteration i where the current song is the one with beauty b_min that appears last among all songs with that beauty? Or the iteration when we have processed all songs with beauty >= b_min (including all songs in T) and we are at some song with beauty b_min? Actually we need to find an index i such that after processing some song with beauty = b_min, the heap's sum S_i is at least the sum of lengths in T, and b_i = b_min. Then S_i * b_min >= sum(T) * b_min, so candidate >= pleasure(T). So if such i exists, then max candidate >= pleasure(T). So algorithm's answer is an upper bound on optimal? Wait, we want to compute max pleasure, so we take max over candidates. If for every valid set T, there is some candidate >= pleasure(T), then the maximum candidate is at least the optimal pleasure. On the other hand, each candidate corresponds to some specific set? Not exactly; but candidate is S_i * b_i, and S_i is sum of some set of at most k songs (the heap). However, the heap set's minimum beauty may be > b_i, so the actual pleasure of that heap set is S_i * (min beauty of heap set) which is >= S_i * b_i. So S_i * b_i <= actual pleasure of that heap set. Therefore, the candidate is less than or equal to the pleasure of some valid set (the heap set). So candidate <= some valid pleasure. Hence, the maximum candidate is <= maximum possible pleasure? Not necessarily: The maximum candidate might be less than the maximum pleasure because it's a lower bound for the heap set's pleasure, but the heap set's pleasure could be higher. However, we are taking max over candidates. For the heap set that achieves optimal pleasure, its pleasure is P_opt. There is some iteration i where the heap contains that set (or a set with sum >= that sum and min beauty >= b_min of that set). But we compute candidate S_i * b_i, which could be less than P_opt if b_i is less than the min beauty of that set. However, at the iteration where b_i equals the min beauty of that optimal set, the heap may have sum >= sum_opt, giving candidate >= P_opt? Let's examine: Suppose optimal set T* has sum S_opt, min b_min. Consider iteration i when we process the song with beauty b_min. At that point, the heap contains the k largest lengths among songs processed so far (beauty >= b_min). Since T* is a subset of those songs of size <= k, the sum of the k largest lengths is at least S_opt. So S_i >= S_opt. Then candidate = S_i * b_min >= S_opt * b_min = P_opt. So the max over i will be at least P_opt. Also, any candidate corresponds to S_i * b_i, and we can argue that there exists a valid set (the heap set) whose pleasure is at least S_i * b_i (since min beauty of heap set >= b_i, so its pleasure >= S_i * b_i). Therefore, the maximum candidate is actually equal to the maximum pleasure: because the maximum candidate is at least P_opt, and also for each candidate, there is a valid set with pleasure at least that candidate, so the maximum pleasure is at least the maximum candidate. Combining: max candidate <= max pleasure (since each candidate <= some valid pleasure, but the maximum over candidates could be less than or equal to the maximum over valid pleasures? Actually if each candidate is <= some valid pleasure, then the max over candidates is <= the max over valid pleasures. But also we have max candidate >= P_opt = max pleasure. So max candidate = max pleasure. So indeed the algorithm is correct.
Thus both methods (candidate before adding plus heap of size k-1, or adding then candidate with heap of size k) are valid. The difference is in handling of the current song. Let's check equivalence:
Method A (described first): heap holds top (k-1) from previous songs, candidate = (t_i + sum_prev) * b_i, then add t_i to heap (size k-1). This ensures that the set considered includes current song. This yields a candidate that exactly equals pleasure of set: current song plus top (k-1) from previous. That set is valid and its min is b_i. So candidate is exact pleasure of a specific set. Over all i, we consider n sets, and the optimum among these sets is the answer. But is it possible that the optimal set is not of this form (i.e., includes current song and top (k-1) from previous)? Suppose the optimal set has min beauty b_min and includes some song with beauty b_min, but the other songs are not exactly the top (k-1) lengths among songs with higher beauty because maybe including all top (k-1) lengths would cause the set to have more than k? Actually it would be exactly k if there are at least k-1 higher beauty songs. But what if the optimal set includes multiple songs with beauty equal to b_min, and not all of the top lengths from higher beauty? Could that yield a higher product? Let's reason: For a fixed min beauty b_min, we want to maximize sum of lengths subject to at most k songs, all with beauty >= b_min, and at least one with beauty exactly b_min. The maximum sum is achieved by taking the songs with the largest lengths among those with beauty >= b_min, but we must include at least one with beauty exactly b_min. If the set of top k lengths among songs with beauty >= b_min already includes at least one with beauty exactly b_min, then that set is feasible and optimal. If not, then all top k lengths have beauty > b_min, so we need to replace the smallest among them with the best available song having beauty exactly b_min to satisfy the constraint. This might yield a slightly lower sum than the unrestricted top k sum, but could still be optimal. In our method A, when we iterate over each song i as minimum, we consider exactly: include i, and then the top (k-1) from previous songs (which are those with higher beauty, not equal). This set may not be optimal if there are multiple songs with same beauty b_i, and the optimal set might include more than one of them and fewer from higher beauty. For instance, consider b values: two songs with beauty 10: t=100 and t=1; one song with beauty 9: t=99. k=2. We can choose at most 2 songs. The possible sets:
Choose both beauty 10 songs: sum=101, min=10 => 1010.
Choose the large beauty 10 and beauty 9: sum=199, min=9 => 1791.
Choose the small beauty 10 and beauty 9: sum=100, min=9 => 900.
Choose just one: 10010=1000, 110=10, 99*9=891.
Optimal is 1791 (beauty 9 and large beauty 10). But that set's min is 9, with songs: beauty 9 (t=99) and beauty 10 (t=100). That set includes a song with min beauty (9) and one higher beauty. Our method A: Sort by b descending: first (b=10,t=100), then (b=10,t=1), then (b=9,t=99). For i=1 (first b=10,t=100): previous songs none, candidate = (100+0)*10=1000. Add t=100 to heap (k-1=1). Heap now has {100} (largest 1 among previous? Actually heap capacity 1, contains 100). For i=2 (second b=10,t=1): candidate = (1 + sum(heap)? sum=100) => (1+100)10=1010. So captures set of both beauty 10's (1010). Then add t=1: heap size 1, compare with top (100); 1<100 so not added. Heap remains {100}. For i=3 (b=9,t=99): candidate = (99 + sum(heap)=100) * 9 = 1999=1791. That's the optimal. So method A captured it. Notice that for the optimal set, the minimum is b=9, and the other song is from higher beauty (b=10, t=100). That's exactly "current song plus top (k-1) from previous songs", because previous songs are those with higher beauty (b=10). So it works.
Now consider a scenario where the optimal set includes two songs with the same min beauty and one with higher beauty, and the top (k-1) from previous (higher beauty) might be suboptimal because we are forced to include the current song and can only take (k-1) others; but if we have multiple songs with same min beauty, maybe we want to include more than one of them and drop some higher beauty songs if the higher beauty songs have low lengths. For fixed min b, we want to maximize sum of lengths given we must include at least one with beauty exactly b. The optimal is: take the top k lengths from the set of songs with beauty >= b, but if among those top k, none have beauty exactly b, then we need to replace the smallest among them with the largest song having beauty exactly b (since we must include at least one). That replacement might be better than taking the unrestricted top k (which would have min > b but sum slightly larger?). Actually let's compare: Let S_topk = sum of k largest lengths among all songs with beauty >= b. Let the smallest among those k have length L_min_top. Let the largest length among songs with beauty exactly b be L_max_b. If L_max_b > L_min_top, then the set formed by replacing that smallest with the max b song would have sum = S_topk - L_min_top + L_max_b, which could be larger than S_topk? Possibly if L_max_b > L_min_top, then sum increases. But also the min beauty becomes b (since we included a b song). If L_max_b <= L_min_top, then the unrestricted top k set may already include a b song? Not necessarily; even if L_max_b <= L_min_top, the top k set might not contain any b song, but replacing would decrease sum, so the optimal would be to still take the top k set but then its min beauty > b, so its product would be at least S_topk * (b+ something). That set would be considered when the min beauty is higher. So for min b, the optimal sum is either S_topk if there is at least one b song in the top k, else max(S_topk - L_min_top + L_max_b, maybe also consider taking fewer than k? But if we take exactly k, that's the best possible sum for that min b). So the optimal sum for min b is not simply t_i + sum of top (k-1) from higher beauty, because it might be beneficial to include multiple b songs if they are long and some higher beauty songs are short.
But our method A considers for each song i (with beauty b_i), the set: {i} ∪ (top (k-1) songs with beauty > b_i). It does not consider including other songs with beauty equal to b_i besides i. However, as argued earlier, the optimal set with min b_i could include other songs with equal beauty, and our method may miss that if the other equal-beauty songs have higher lengths than some of the higher-beauty songs we selected. But is it possible that the optimal set with min b_i includes another song j with same beauty b_i, and excludes some higher-beauty song, and yields a larger product than the set consisting of i plus the top (k-1) higher-beauty songs? Let's try to construct a counterexample.
Suppose we have:
Songs with beauty > b: A1 (t=10), A2 (t=9) - both higher beauty.
Songs with beauty = b: B1 (t=100) (this is i), B2 (t=95) (another).
k = 2.
We want min beauty = b. The candidate from method A for i = B1 (t=100) would be: include B1 and the best higher-beauty song (since k-1=1). The best higher-beauty song is A1 t=10, sum=110 => pleasure=110b. But the optimal set with min b could be B1 and B2: sum=195 => pleasure=195b, which is larger. Would method A capture this? It would capture when i = B2? For i = B2 (t=95), candidate = 95 + best higher-beauty = 95+10=105 => 105b, still not 195. So neither B1 nor B2 give 195 because when processing B1, B2 is not yet in the heap (since same beauty and we process B1 before B2? If we process in some order, B2 might be after B1, so when processing B1, B2 is not in previous (higher beauty) because it has equal beauty, not higher. When processing B2, B1 is already in heap? If we add songs to heap after processing, then when processing B2, B1 has been added to heap (since we processed B1 earlier and added it). But B1 has equal beauty, not higher. However our method A only adds songs to heap after processing, and the heap is used for "previous songs" which are those with beauty > current? Actually we said we add song to heap after using it, so for B2, the previous songs include B1 because we processed B1 earlier. But B1 has same beauty, not higher. So in the candidate for B2, sum includes B1 (if it is among the top (k-1) lengths from previous songs). But note: Our earlier description said we maintain heap of top (k-1) lengths among previous songs, where previous songs are those processed earlier. Since we sorted descending by beauty, earlier songs have beauty >= current beauty. So for B2, previous songs include those with beauty > b and also those with beauty = b that appear earlier. So in the candidate for B2, we can include B1 if its length is among the top (k-1) among previous songs. In our example, k=2 => k-1=1. So we need to pick the single largest length among previous songs. That would be max(A1(10), maybe also B1(100) if B1 is earlier. Suppose order: we sort by beauty descending, but both B1 and B2 have same b, so their order can be arbitrary. If we order B1 before B2, then for B2, previous songs include B1 (t=100) and A1 (t=10), etc. The top (k-1)=1 length among previous is 100 (B1). Then candidate for B2 = (t_B2=95 + 100) * b = 195b. That's exactly the optimal set! So method A captures it when we process the later of the equal-beauty songs. So indeed, by processing in descending beauty, the later songs with equal beauty can include earlier ones as "previous" (since they have beauty >= current). Therefore, the set that includes multiple equal-beauty songs will be considered when the last of them (in the sorted order) is processed as the minimum, because all other equal-beauty songs are in the previous set. So the candidate for that last song corresponds to taking that song plus the top (k-1) among all songs with beauty >= b (including other equal-beauty songs). That yields a set where the minimum is b (since the last song is the smallest in the sorted order among those with that beauty? Actually all have same b, so min is still b). And that set could include multiple equal-beauty songs. So method A indeed considers all possible sets: For any set with min b, if we take the song with that beauty that appears last in the sorted order among the chosen songs, then all other chosen songs appear earlier (since they have beauty >= b and if they have same beauty, they appear earlier if we order them arbitrarily, but we can assume we process them in some order; we need to ensure that the last chosen song is processed after all others. In our iteration, we consider each song as candidate minimum, and we take top (k-1) from previous songs. For a given optimal set, let the song with the minimum beauty that appears last in the sorted order be the "pivot". Then all other songs in the set appear earlier. Since our algorithm considers that pivot, and selects the top (k-1) from previous songs, it may not select exactly the other songs in the set if they are not among the top (k-1) lengths among all previous songs. But the sum of the top (k-1) lengths among all previous songs is at least the sum of the lengths of the other songs in the set (since the set has at most k-1 other songs, and they are a subset of previous songs). Therefore, (t_pivot + sum_top_{k-1}) >= sum(T). Thus candidate >= pleasure(T). So the algorithm's candidate for that pivot is at least the pleasure of the optimal set. Then later we take max, so answer >= optimal. But also each candidate corresponds to a specific set (pivot + top (k-1) previous), whose pleasure is exactly the candidate (since min = b_pivot). That set's pleasure is ≤ optimal (since optimal is maximum). So the max candidate is ≤ optimal. Combining gives equality. So method A is correct.
Thus both methods are valid.
Now, we should implement one. The first method (candidate before adding, heap size k-1) is straightforward and ensures candidate exactly corresponds to a valid set. The second method (add then candidate, heap size k) is also valid and maybe simpler because we don't need to treat k=1 specially? Actually both treat k=1 similarly. The second method: if k=1, we add t, if heap size > 1? Actually we set heap size limit to k. For k=1, we add t, then if heap size > 1 (i.e., >1) we pop smallest; but after adding first song, size=1, not >1; then candidate = sum * b. That gives t*b for each song, and we take max. After adding next, heap size would become 2? Actually we add each song: after adding second, size=2 >1, so we pop smallest. The heap will always contain only the largest t seen so far. Then candidate = that largest t * current b. That might produce values that are not necessarily the product of the current song, but could be product of a larger t from previous song times current b, which might be larger than actual feasible product because the set consisting of that previous song alone would have min beauty its own b, not current b. But does candidate exceed optimal? Let's test with k=1. Sorted descending b. At step i, heap contains the largest t among songs 0..i. Then candidate = max_t_sofar * b_i. For i where b_i is small, this could be huge if there is a large t earlier. But is max_t_sofar * b_i a valid pleasure? The set consisting of just the song with that max_t has beauty b_max, and its pleasure is max_t * b_max. If b_i < b_max, then max_t * b_i is less than max_t * b_max, which is a valid product, so it's not exceeding optimal. Actually max_t * b_i could be less than or equal to max_t * b_max. So it's safe. And max over i of max_t_sofar * b_i will eventually be at least max_t * b_max when i corresponds to the song with that max_t (since at that step, max_t_sofar includes that song, and b_i = b_max). So answer = max_t * b_max. So it's correct. So second method works for k=1 as well.
Given the simplicity, we could implement the second method: after adding, maintain heap of size k (or at most k). But careful: In second method, we add before computing candidate. That means at step i, the heap includes the current song. Then we maintain size k. Then candidate = sum * b_i. That yields candidate for current beauty. However, note that if k is large, the heap may include the current song, but also might pop it if it's too small? Actually when we add current song, we push t_i. If heap size exceeds k, we pop the smallest t. So it's possible that the current song gets popped immediately if it's among the smallest. That's okay. Then candidate uses the heap after popping. So the set represented by the heap might not include the current song. However, we still compute sum * b_i. But as argued earlier, the algorithm is correct.
Which method to implement? I think both are fine. I'll likely implement the first method because it's more intuitive to me: candidate before adding ensures the set includes the current song. But we must be careful with heap capacity k-1. For k=1, we skip addition. That's fine.
Let's double-check potential overflow: sum can be up to k * max_t = 3e5 * 1e6 = 3e11, times b up to 1e6 = 3e17, fits in 64-bit (max 9e18). Use long long.
Now, we need to handle input size efficiently.
Pseudo-code:
read n,k
songs = []
for i in 0..n-1:
read t,b
songs.append((b,t)) // store beauty first for sorting
sort songs by b descending (if same b, order doesn't matter)
min_heap (min-heap) for lengths, capacity = k-1
sum = 0
ans = 0
for each (b,t) in songs:
cur = (sum + t) * b
if cur > ans: ans = cur
if k > 1:
if min_heap.size() < k-1:
min_heap.push(t)
sum += t
else:
if t > min_heap.top():
sum -= min_heap.top()
min_heap.pop()
min_heap.push(t)
sum += t
print ans
Edge case: When k=1, min_heap not used; sum remains 0; cur = t*b; ans max of those. Works.
Now consider scenario where optimal set includes 3 songs, with min beauty from a song that is not the smallest among its beauty? Already covered.
Now test scenario where k=3, and optimal set uses 2 songs? Our algorithm will consider sets of size up to k. If a set of 2 yields higher product, it will still be considered because for some i, the candidate might be based on sum of top (k-1) previous, but if there are fewer than k-1 previous, sum is sum of all previous, so the candidate might have size less than k. Example: n=2,k=3, songs: (t=100,b=10), (t=1,b=9). Sorted: (10,100),(9,1). k-1=2. i1: sum=0, cur=100*10=1000. ans=1000. Add 100 to heap (size<2 push, sum=100). i2: cur=(1+100)9=1019=909. ans=1000. So max is 1000, which is the single song product. That's correct. So sets of size <k are considered when there are not enough previous songs to fill to k, but also could a set of size 2 be optimal when there are enough songs to fill to k but we choose not to? As argued earlier, if adding a song increases sum and doesn't lower min, product increases. So if there is a third song with positive length and beauty >= min, adding it would increase product. So a set of size < k cannot be optimal unless there are not enough songs with beauty >= min, i.e., total number of eligible songs < k. But is it possible that adding a song with positive length but very small length could reduce the min? No, because min stays same. So product increases by length * min, which is positive. So indeed for a fixed min, we want as many songs as possible. So the only reason to take fewer than k is if there aren't enough eligible songs. So our algorithm handles that.
Thus solution is correct.
Now, complexity: O(n log n) due to sorting, plus O(n log k) for heap ops. For n=3e5, fine.
Now, we need to output answer as integer.
Potential pitfalls: Using int for sum may overflow, so use long long.
Implementation details:
We'll define vector<pair<int, int>> songs; first = b, second = t.
sort with greater comparator: sort(songs.begin(), songs.end(), greater<>()) or provide lambda.
Use priority_queue<int, vector, greater> pq.
long long total = 0;
long long ans = 0;
int limit = k - 1;
for (auto &p : songs) {
int b = p.first, t = p.second;
long long cur = (total + t) * b;
if (cur > ans) ans = cur;
if (k > 1) {
if (pq.size() < limit) {
pq.push(t);
total += t;
} else if (limit > 0) { // implies pq.size() == limit
if (t > pq.top()) {
total -= pq.top();
pq.pop();
pq.push(t);
total += t;
}
}
}
}
Print ans.
We should also handle the case where limit = 0 (k=1) separately to avoid unnecessary ifs.
But we can also implement the second method which may be simpler:
for each song:
pq.push(t);
sum += t;
if (pq.size() > k) {
sum -= pq.top();
pq.pop();
}
ans = max(ans, sum * b);
print ans.
Yes, that's even simpler and avoids special case k=1. Let's test with k=1: At each step, push t, sum+=t, pq.size() becomes 1, then if size > 1? No, so no pop. Then ans = max(ans, sum * b). That's tb for each. After next song, push t2, sum becomes t1+t2, size=2 > 1, so pop smallest, sum becomes max(t1,t2). So after second song, heap contains the larger t, ans = max(prev ans, larger_t * b2). This will eventually consider the max t times its own b? Actually when we process the song with the largest t, say at index i, sum becomes that t (since after adding, heap might have that t only if it's larger than previous ones? Let's simulate: Songs sorted by b descending: Suppose largest b song has t=5, next b has t=10. Process first: heap {5}, sum=5, ans =5b1. Process second: push 10, sum=15, size=2>1, pop smallest (5), sum=10, ans = max(prev, 10b2). If b2 is lower than b1, 10b2 might be less than 5b1. So the max might be 5b1. However, optimal could be 10b2 if b2 is high enough? Actually if b2 is lower, 10b2 might be less. But what about the set consisting of just the song with t=10? Its pleasure is 10 * b2. That's captured. And also, if we later process a song with even larger b? Actually sorted descending, so b2 <= b1. So the maximum product among single songs is max over i of t_ib_i. Our algorithm's ans after all steps will be that max because for each i we compute t_ib_i? Not exactly; when processing song i, after push and possible pop, sum may not equal t_i; it may be the max t among seen so far. For i where t_i is not the max, after adding, it might be popped immediately, and sum becomes the current max t (from earlier). Then we compute sum * b_i, which is not necessarily t_ib_i. But we also compute earlier at the step of the max t song, we computed its own tb. So the maximum over i of t_ib_i will be included. So ans will be at least that. Could ans be larger than max over single songs? For k=1, max pleasure is exactly max over single songs. So ans must equal that. Let's ensure: Suppose we have songs: (t=5,b=100) and (t=100,b=1). Sorted: (100,5), (1,100). Process first: push 5, sum=5, ans=5100=500. Process second: push 100, sum=105, size=2>1, pop smallest (5), sum=100, ans = max(500, 1001=100) =500. So correct. If we had (t=100,b=50) and (t=1,b=100): sorted: (100,1), (50,100). Process first: ans=1100=100. Process second: push 100, sum=101, pop smallest 1? Actually heap after first: {1}. After second: push 100, sum=101, size=2>1, pop smallest which is 1, sum=100, ans = max(100, 100*50=5000) =5000. That's t=100,b=50, which is a valid single song product. So ok.
Thus the second method works for k=1 as well.
Now, check with the earlier example where we thought the second method might overcount? It's safe because ans is max over sum*b_i, and we argued it's equal to optimum.
Proof sketch for method 2: For any set T of size ≤ k, let b_min = min_{j∈T} b_j. When we process the song with beauty b_min (the one that appears last among T in sorted order), after inserting it, the heap contains the k largest lengths among songs with beauty ≥ b_min. Since T is a subset of those songs, sum(T) ≤ current sum. Hence sum_current * b_min ≥ sum(T) * b_min = pleasure(T). So ans ≥ pleasure(T). Conversely, at each step, the heap corresponds to some set H of at most k songs (the ones currently in the heap). The pleasure of H is sum(H) * min_beauty(H) ≥ sum(H) * b_i, because min_beauty(H) ≥ b_i. So ans ≤ max_{valid sets} pleasure. Hence ans = optimum.
Thus we can implement the simpler second method.
Implementation details for method 2:
Read n,k.
songs = list of (b, t).
Sort songs by b descending.
priority_queue<int, vector, greater> minHeap;
long long sum = 0;
long long ans = 0;
for each (b,t) in songs:
minHeap.push(t);
sum += t;
if (minHeap.size() > k) {
sum -= minHeap.top();
minHeap.pop();
}
ans = max(ans, sum * b);
print ans.
We need to be careful about the order: push then possibly pop, then compute candidate. This ensures heap size ≤ k. When heap size < k, sum is sum of all processed songs? Actually if heap size < k, it means we haven't processed k songs yet; but we have pushed all processed songs into heap, and since size < k, we haven't popped any, so heap contains all processed songs. That's fine: the set of all processed songs has size i+1, which may be less than k, and sum of all of them is the sum. However, is it valid to take all processed songs? They all have beauty ≥ current b_i, yes. So the candidate corresponds to sum of all processed songs times b_i. That's a valid set? The set of all processed songs might have min beauty equal to b_i? Not necessarily; the min beauty among processed songs is b_i (since current song has beauty b_i and all earlier have beauty >= b_i, but some earlier may have beauty equal to b_i? Actually if there are other songs with same beauty that were processed earlier, then min beauty among processed songs is still b_i (since current is the lowest among them? If earlier songs have same beauty, then min is still b_i because current has same beauty, but the minimum is b_i. So the set of all processed songs has min beauty exactly b_i if the current song is the smallest beauty among processed ones. Since we are processing in decreasing order, the current song has the smallest beauty among those processed so far (because we go from high to low). So indeed, at each step, the current b_i is the minimum among all songs processed up to that point. So the set of all processed songs has min = b_i. However, if we have more than k processed songs, we pop the smallest lengths to keep only k largest. Then the heap contains exactly k songs (the largest lengths) among processed songs. The min beauty of the heap set may be larger than b_i, because we might have popped a song with low length that possibly had beauty b_i? The popped song is the smallest length, not necessarily the one with min beauty. So the heap set could consist of songs all with beauty > b_i. But we still compute candidate = sum(heap) * b_i. As argued, that's a lower bound for the heap set's pleasure. But as earlier reasoning, the algorithm still yields correct optimum. So method 2 is sound.
Given its simplicity, I'll go with method 2.
Let's test method 2 on a tricky case: n=3, k=2, songs: (b=10,t=1), (b=9,t=100), (b=8,t=1000). Sorted: (10,1), (9,100), (8,1000). Process:
i2: push 1000, heap size becomes 3 >2, so pop smallest (1), sum=101+1000-1=1100? Actually after push, sum=101+1000=1101, size=3, pop smallest (1), sum=1100, heap now contains {100,1000}, ans = max(909, 1100*8=8800) => 8800. The optimal set? Let's check: All songs, but can only take 2. Options:
(1,10) and (100,9): sum=101 min9=909.
(1,10) and (1000,8): sum=1001 min8=8008.
(100,9) and (1000,8): sum=1100 min8=8800.
Single: 110=10, 1009=900, 1000*8=8000.
So optimal is 8800, matches candidate at i2. Good.
Now test with equal beauty and potential need to include multiple equal beauty: n=3,k=2, songs: (b=10,t=5), (b=10,t=8), (b=9,t=100). Sorted: we can order equal beauty arbitrarily; let's say (10,5), (10,8), (9,100). Process:
i2: push100, size becomes 3>2, pop smallest (5), sum=13+100-5=108, heap now contains {8,100}, ans=max(130,108*9=972) =>972. That's the optimal set {8,100}? Actually {8,100} min=9 gives 972. But what about set {5,8}? That's 130. So optimal is 972. Works.
Now test with scenario where optimal set includes two equal beauty and one higher? k=3, songs: (b=10,t=5), (b=10,t=8), (b=9,t=100), (b=9,t=1) maybe? Let's try: n=4,k=3, songs: (10,5),(10,8),(9,100),(9,1). Sorted: (10,5),(10,8),(9,100),(9,1). Process:
i0: push5 sum=5 ans=50
i1: push8 sum=13 ans=130 (heap size 2)
i2: push100 sum=113 ans=max(130,1139=1017) ->1017 (heap size 3)
i3: push1 sum=114, size becomes 4>3, pop smallest? heap currently has 5,8,100? Actually after i2, heap contains 5,8,100 (since we never popped). Now push1, sum=114, size=4>3, pop smallest (1? Wait the heap is min-heap; after push1, the heap contains 5,8,100,1. The smallest is 1. We pop 1, sum=113, heap now contains 5,8,100. ans = max(1017, 1139=1017) ->1017. So ans=1017. What are possible sets? We can take up to 3. Consider set {8,100,5}? That's all three with b>=9? Actually {8,100,5} includes two b=10 and one b=9, min=9, sum=113 => 1017. That's exactly the candidate at i2 and i3. Set {5,8,100} same. Could there be a set {100,1,8}? sum=109 min=9 =>981, less. So optimal 1017. Good.
Now consider scenario where we might want to pick less than k songs even though there are more available because including a song would reduce min beauty? That's not an issue because min beauty is determined by the smallest beauty among chosen songs. If we include a song with lower beauty, the min becomes lower. But if we are considering a specific candidate min beauty, we restrict to songs with beauty >= that min. So adding songs with higher beauty doesn't lower min. So for a fixed min, we add as many as possible.
Thus method 2 appears correct.
Now, regarding the case where k=0? Not allowed (k>=1).
We'll implement method 2.
Now, we must consider that the sum * b could exceed 2^63? 3e11 * 1e6 = 3e17 < 9.22e18, so fits in signed 64-bit.
Now, we can implement.
Potential pitfalls: sorting with b descending; if we store as pairs (b, t), we can sort by first descending. In C++, by default sort sorts by first then second ascending. So we can use sort(songs.rbegin(), songs.rend()) to sort descending by first? Actually rbegin, rend will reverse the order, which would sort ascending and then reverse, not efficient but works. Better to use custom comparator: sort(songs.begin(), songs.end(), [](auto &a, auto &b) { return a.first > b.first; }).
Now, the heap: we need a min-heap. Use priority_queue<int, vector, greater> pq.
Now, input: up to 3e5 lines, use scanf or fast ios.
Now, produce output.
Let's implement.
Edge Cases: n = k = 3e5, all t=1e6, b=1e6. Then sum at final step = k * 1e6 = 3e11, times b=1e6 => 3e17, fits. Works.
Now, test with random small cases via brute-force to verify. But in analysis we trust.
Double-check proof for method 2 more formally: The algorithm computes ans = max_{i} (S_i * b_i) where S_i is sum of the k largest lengths among songs with beauty >= b_i (including the i-th). Actually S_i is sum of the min(k, i+1) largest lengths among the first i+1 songs (since we maintain heap of largest k among processed). But does S_i equal exactly sum of k largest among songs with beauty >= b_i? Since processed songs are exactly those with beauty >= b_i (because sorted descending), yes. So S_i = sum of k largest t among songs with beauty >= b_i (or all if fewer than k). So for each i, S_i * b_i is computed.
Now, consider any optimal set T of size m ≤ k. Let b_min = min_{j∈T} b_j. Since songs are sorted by b descending, let i be the index of the song in T with beauty b_min that appears last in the sorted order (i.e., with smallest index? Actually descending order: highest b first, lowest b last. So the song with the minimum beauty will be among the later indices. For convenience, take the song in T with minimum beauty; if multiple, take the one that appears last (i.e., with smallest index in sorted order? Wait descending: first elements have larger b, last elements have smaller b. So the minimum beauty song will be among the later indices (higher index). Choose the one with the maximum index among T. That song, say at index i, has beauty b_i = b_min. Then all other songs in T have beauty >= b_min and appear before i (since they have higher or equal beauty, but if equal, they could be before or after depending on order; we can ensure that we order equal beauty such that the chosen minimum is the last among equal beauty songs in T; if we process in any order, we can pick the one that appears last in the sorted order. Since we have control over sorting, but ties can be arbitrary. So we can define i as the maximum index among indices of songs in T. Then all songs in T are among indices <= i. Thus they are all processed before or at i. At the moment after processing i (i.e., in the iteration for i), the heap contains the k largest t among songs with indices 0..i. Since T is a subset of these songs and |T| ≤ k, we have sum(T) ≤ S_i (the sum of the k largest). Hence S_i * b_min ≥ sum(T) * b_min. So ans ≥ that product. So ans >= optimal.
Conversely, for each i, consider the set H_i consisting of the songs currently in the heap (size ≤ k). Let b_min(H_i) be the minimum beauty among those songs. Since all songs in H_i have beauty >= b_i (they are from indices <= i), we have b_min(H_i) ≥ b_i. Then pleasure(H_i) = sum(H_i) * b_min(H_i) ≥ sum(H_i) * b_i = S_i * b_i. So the actual maximum pleasure is at least S_i * b_i? Actually pleasure(H_i) is some valid pleasure, so max_pleasure ≥ pleasure(H_i) ≥ S_i * b_i. Therefore max_pleasure ≥ max_i S_i * b_i = ans. Combining, ans = max_pleasure. So algorithm correct.
Great.
Now, let's think about implementation details: We'll need to use 64-bit integers. In C++:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int n, k;
cin >> n >> k;
vector<pair<int, int>> songs(n);
for (int i = 0; i < n; i++) {
int t, b;
cin >> t >> b; // but we want beauty first for sorting, so store as (b, t)
songs[i] = {b, t};
}
sort(songs.begin(), songs.end(), [](const auto &a, const auto &b) {
return a.first > b.first;
});
priority_queue<int, vector, greater> pq; // min-heap
ll sum = 0;
ll ans = 0;
for (auto &[b, t] : songs) {
pq.push(t);
sum += t;
if (pq.size() > k) {
sum -= pq.top();
pq.pop();
}
ans = max(ans, sum * b);
}
cout << ans << endl;
return 0;
}
But note: In the for loop, we use structured binding: auto &[b, t]. That's C++17. In older, use tie.
Now, test on provided examples.
Example 1:
4 3
4 7
15 1
3 6
6 8
Our code reads t,b? Actually we read t and b but then store as (b,t). In input lines: "4 7" -> t=4,b=7 => store (7,4). Similarly (15,1) -> (1,15); (3,6) -> (6,3); (6,8) -> (8,6). Sorted by b descending: (8,6), (7,4), (6,3), (1,15). Then as computed earlier: ans=78. Good.
Now, test with large values to ensure no overflow.
Now, finalize solution.
But I'd like to reflect: The problem states "at most k songs", but we are effectively always taking exactly k songs if available, but as argued it's optimal. However, could there be a scenario where taking exactly k songs leads to a product less than taking fewer because of integer constraints? Since all numbers positive, adding a song adds length * min_beauty > 0, so product increases. So it's always beneficial to include as many as possible. So yes.
One more nuance: Suppose we include a song with zero length? But t_i >= 1, so positive.
Thus solution stands.
Now, we should produce the final answer.
But we need to be absolutely sure about method 2 correctness. Let's attempt to construct a potential counterexample where ans computed by method 2 is not equal to the optimum, perhaps due to the heap not including the minimum beauty song. Consider: n=2,k=2, songs: (b=5,t=10), (b=4,t=100). Sorted: (5,10), (4,100). Process:
i0: push10 sum=10 ans=105=50
i1: push100 sum=110, size=2, ans=max(50,1104=440) =>440.
Optimal sets: {10,5} gives 105=50; {100,4} gives 1004=400; both gives (110)*4=440? Wait both includes both: sum=110, min=4 =>440. So optimal 440. matches.
Now, consider a case where the heap after popping might exclude the current song, but the candidate uses current b which is lower than the heap's min beauty, so product might be less than the heap set's actual pleasure. However, we already covered that the maximum over i will still capture the optimum. But could the algorithm ever produce a candidate that is larger than any feasible pleasure? That would be problematic. Let's see: At step i, S_i * b_i is computed. Is it possible that there is no set of at most k songs with pleasure >= S_i * b_i? Suppose the heap set H has sum S_i and min beauty b_min(H) > b_i. Then the pleasure of H is S_i * b_min(H) > S_i * b_i. So there exists a set (namely H) with pleasure greater than S_i * b_i, so it's not an overestimate beyond feasible. But could S_i * b_i be larger than the pleasure of H? That would mean S_i * b_i > S_i * b_min(H) => b_i > b_min(H) which is false since b_i <= b_min(H). So S_i * b_i <= pleasure(H). Therefore, every candidate is ≤ some feasible pleasure. So ans ≤ max feasible pleasure. And we already have ans ≥ max feasible pleasure. So equality.
Thus method 2 is safe.
Now, we need to consider one more nuance: The problem says "at most k songs". Our heap maintains exactly k largest lengths if there are at least k processed songs. However, what if the optimal set uses fewer than k songs, and we are at a step where heap contains k songs? That candidate may be based on k songs, but that's fine because that candidate's pleasure is at least as large as the optimum? Actually if the optimal set uses fewer than k songs, that means there are fewer than k songs with beauty >= b_min (since otherwise you'd add more to increase product). So at the step corresponding to b_min, the total number of processed songs (with beauty >= b_min) is less than k, so the heap size will be less than k, and S_i = sum of all those songs (since we don't pop). So candidate = sum(all) * b_min, which is exactly the pleasure of taking all eligible songs (which is the optimal, as argued). So ans will be that. So fine.
Thus final solution is ready.
Now, we can produce final answer.
One more check: Input constraints up to 300k, so we should avoid recursion, use iterative.
Now, write final code.
I'll include comments for clarity.
Now, go to final. ```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, k;
cin >> n >> k;
vector<pair<int, int>> songs(n); // (beauty, length)
for (int i = 0; i < n; ++i) {
int t, b;
cin >> t >> b;
songs[i] = {b, t};
}
// sort by beauty decreasing
sort(songs.begin(), songs.end(),
[](const auto& a, const auto& b) { return a.first > b.first; });
// min‑heap of lengths, keeps the k largest among processed songs
priority_queue<int, vector<int>, greater<int>> minHeap;
ll sum = 0; // sum of lengths currently in the heap
ll ans = 0;
for (auto [b, t] : songs) {
minHeap.push(t);
sum += t;
if (int(minHeap.size()) > k) {
sum -= minHeap.top();
minHeap.pop();
}
ans = max(ans, sum * b);
}
cout << ans << "\n";
return 0;