Choosing flowers (Codeforces 1379C)
Tags: Greedy, two pointers

Vladimir would like to prepare a present for his wife: they have an anniversary! He decided to buy her exactly $$$n$$$ flowers.Vladimir went to a flower shop, and he was amazed to see that there are $$$m$$$ types of flowers being sold there, and there is unlimited supply of flowers of each type. Vladimir wants to choose flowers to maximize the happiness of his wife. He knows that after receiving the first flower of the $$$i$$$-th type happiness of his wife increases by $$$a_i$$$ and after receiving each consecutive flower of this type her happiness increases by $$$b_i$$$. That is, if among the chosen flowers there are $$$x_i > 0$$$ flowers of type $$$i$$$, his wife gets $$$a_i + (x_i - 1) \cdot b_i$$$ additional happiness (and if there are no flowers of type $$$i$$$, she gets nothing for this particular type).Please help Vladimir to choose exactly $$$n$$$ flowers to maximize the total happiness of his wife.

Input: The first line contains the only integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$), the number of test cases. It is followed by $$$t$$$ descriptions of the test cases.Each test case description starts with two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le m \le 100\,000$$$), the number of flowers Vladimir needs to choose and the number of types of available flowers.The following $$$m$$$ lines describe the types of flowers: each line contains integers $$$a_i$$$ and $$$b_i$$$ ($$$0 \le a_i, b_i \le 10^9$$$) for $$$i$$$-th available type of flowers.The test cases are separated by a blank line. It is guaranteed that the sum of values $$$m$$$ among all test cases does not exceed $$$100\,000$$$.

Output: For each test case output a single integer: the maximum total happiness of Vladimir's wife after choosing exactly $$$n$$$ flowers optimally.

Note: In the first example case Vladimir can pick 1 flower of the first type and 3 flowers of the second type, in this case the total happiness equals $$$5 + (1 + 2 \cdot 4) = 14$$$.In the second example Vladimir can pick 2 flowers of the first type, 2 flowers of the second type, and 1 flower of the third type, in this case the total happiness equals $$$(5 + 1 \cdot 2) + (4 + 1 \cdot 2) + 3 = 16$$$.

Sample Inputs:
2
4 3
5 0
1 4
2 2

5 3
5 2
4 2
3 1

Sample Outputs:
14
16

Solution (Python):
from collections import defaultdict
import sys, math
f = None
try:
    f = open('q1.input', 'r')
except IOError:
    f = sys.stdin
if 'xrange' in dir(__builtins__):
    range = xrange

def print_case_iterable(case_num, iterable):
    print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
    print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
    print(' '.join(A))

def read_int():
    return int(f.readline().strip())

def read_int_array():
    return [int(x) for x in f.readline().strip().split(' ')]

def rns():
    a = [x for x in f.readline().split(' ')]
    return (int(a[0]), a[1].strip())

def read_string():
    return list(f.readline().strip())

def ri():
    return int(f.readline().strip())

def ria():
    return [int(x) for x in f.readline().strip().split(' ')]

def rns():
    a = [x for x in f.readline().split(' ')]
    return (int(a[0]), a[1].strip())

def rs():
    return list(f.readline().strip())

def bi(x):
    return bin(x)[2:]
from collections import deque
import math
NUMBER = 10 ** 9 + 7

def factorial(n):
    M = NUMBER
    f = 1
    for i in range(1, n + 1):
        f = f * i % M
    return f

def mult(a, b):
    return a * b % NUMBER

def minus(a, b):
    return (a - b) % NUMBER

def plus(a, b):
    return (a + b) % NUMBER

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        (g, y, x) = egcd(b % a, a)
        return (g, x - b // a * y, y)

def modinv(a):
    m = NUMBER
    (g, x, y) = egcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
    else:
        return x % m

def choose(n, k):
    if n < k:
        assert false
    return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k)))) % NUMBER
from collections import deque, defaultdict
import heapq
from types import GeneratorType

def bootstrap(f, stack=[]):

    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to
    return wrappedfunc

def dfs(g, timeIn, timeOut, depths, parents):
    cnt = 0
    stack = [[1, 0, 0, 0]]
    while stack:
        (v, neig_i, parent, depth) = stack[-1]
        parents[v] = parent
        depths[v] = depth
        if neig_i == 0:
            timeIn[v] = cnt
            cnt += 1
        while neig_i < len(g[v]):
            u = g[v][neig_i]
            if u == parent:
                neig_i += 1
                continue
            stack[-1][1] = neig_i + 1
            stack.append([u, 0, v, depth + 1])
            break
        if neig_i == len(g[v]):
            stack.pop()
            timeOut[v] = cnt
            cnt += 1
cnt = 0

@bootstrap
def dfs(v, adj, timeIn, timeOut, depths, parents, parent=0, depth=0):
    global cnt
    parents[v] = parent
    depths[v] = depth
    timeIn[v] = cnt
    cnt += 1
    for u in adj[v]:
        if u == parent:
            continue
        yield dfs(u, adj, timeIn, timeOut, depths, parents, v, depth + 1)
    timeOut[v] = cnt
    cnt += 1
    yield

def gcd(a, b):
    if a == 0:
        return b
    return gcd(b % a, a)

def lcm(a, b):
    return a * b / gcd(a, b)

def get_num_2_5(n):
    twos = 0
    fives = 0
    while n > 0 and n % 2 == 0:
        n //= 2
        twos += 1
    while n > 0 and n % 5 == 0:
        n //= 5
        fives += 1
    return (twos, fives)

def shift(a, i, num):
    for _ in range(num):
        (a[i], a[i + 1], a[i + 2]) = (a[i + 2], a[i], a[i + 1])

def equal(x, y):
    return abs(x - y) <= 1e-09

def getAngle(a, b, c):
    ang = math.degrees(math.atan2(c[1] - b[1], c[0] - b[0]) - math.atan2(a[1] - b[1], a[0] - b[0]))
    return ang + 360 if ang < 0 else ang

def getLength(a, b):
    return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
from heapq import heapify, heappush, heappop

def bfs(adj):
    s = set()
    d = defaultdict(set)
    q = deque([])
    s.add(0)
    d[0].add(0)
    q.append((0, 0))
    while len(q) > 0:
        (v, depth) = q.popleft()
        for u in adj[v]:
            if u not in s:
                s.add(u)
                d[depth + 1].add(u)
                q.append((u, depth + 1))
    return d

def dfs(u, top, adj, vis):
    vis[u] = 1
    for (v, d) in adj[u]:
        if vis[v] == 2 or d == 0:
            continue
        if vis[v] == 1:
            return 'No'
        if dfs(v, top, adj, vis) == 'No':
            return 'No'
    vis[u] = 2
    top.append(u)
from bisect import bisect_right

def solution(a, b, both, n, m):
    max_opt = -1
    a.sort(reverse=True)
    a = [-x for x in a]
    prefix = [0]
    for x in a:
        prefix.append(prefix[-1] - x)
    for (l, r) in both:
        i = bisect_right(a, -r)
        if i >= n:
            opt = prefix[n]
        else:
            opt = prefix[i]
            if l >= r:
                opt += (n - i) * r
            else:
                opt += (n - i - 1) * r + l
        max_opt = max(max_opt, opt)
    return max_opt

def main():
    T = 1
    T = ri()
    for i in range(T):
        (n, m) = ria()
        (a, b) = ([], [])
        both = []
        for _ in range(m):
            (l, r) = ria()
            a.append(l)
            b.append(r)
            both.append((l, r))
        x = solution(a, b, both, n, m)
        if 'xrange' not in dir(__builtins__):
            print(x)
        else:
            (print >> output, str(x))
        f.readline()
    if 'xrange' in dir(__builtins__):
        print(output.getvalue())
        output.close()
if 'xrange' in dir(__builtins__):
    import cStringIO
    output = cStringIO.StringIO()
if __name__ == '__main__':
    main()

Solution (Python):
def binary_search(arr, low, high, x):
    mid = (high + low) // 2
    if arr[mid] >= x and (mid + 1 == len(arr) or arr[mid + 1] < x):
        return mid
    elif arr[mid] > x:
        return binary_search(arr, low, mid - 1, x)
    else:
        return binary_search(arr, mid + 1, high, x)

def main(r):
    if r > 0:
        ln = input()
    (n, m) = map(int, input().split())
    lst = []
    max_prev = 0
    a_prev = []
    a_prev_step_sm = [0]
    for i in range(m):
        (a, b) = map(int, input().split())
        lst.append(tuple([a, b]))
    lst = sorted(lst, reverse=True)
    for i in lst:
        a_prev.append(i[0])
        a_prev_step_sm.append(a_prev_step_sm[-1] + i[0])
    k = len(a_prev) - 1
    max_sm = 0
    if len(a_prev_step_sm) - 1 >= n:
        max_sm = a_prev_step_sm[n]
    for i in range(len(lst)):
        if lst[i][1] > max_prev:
            max_prev = lst[i][1]
            while k >= 0 and lst[i][1] >= a_prev[k]:
                k -= 1
            if k >= i:
                if k + 1 >= n:
                    pass
                else:
                    sm = a_prev_step_sm[k + 1] + (n - k - 1) * max_prev
                    max_sm = max(sm, max_sm)
            elif k + 2 >= n:
                pass
            else:
                sm = a_prev_step_sm[k + 1] + a_prev[i] + (n - k - 2) * max_prev
                max_sm = max(sm, max_sm)
    print(max_sm)
if __name__ == '__main__':
    t = int(input())
    for i in range(t):
        main(i)

Solution (Python):
import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
    if _:
        input()
    (n, m) = map(int, input().split())
    a = []
    b = []
    for i in range(m):
        (v1, v2) = map(int, input().split())
        a.append(v1)
        b.append((v2, v1))
    a.sort(reverse=True)
    b.sort(reverse=True)
    c = 0
    l = 0
    summ = 0
    act = 0
    for i in range(m):
        tot = n - l
        while tot and c < m and (a[c] > b[i][0]):
            tot -= 1
            l += 1
            summ += a[c]
            c += 1
        if tot:
            act = max(act, summ + min(b[i]) + b[i][0] * (tot - 1))
        else:
            act = max(act, summ)
    print(act)