Tavas and Karafs (Codeforces 536A)
Tags: Math, binary search

Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs.  Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is si = A + (i - 1) × B.For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero.Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that l ≤ r and sequence sl, sl + 1, ..., sr can be eaten by performing m-bite no more than t times or print -1 if there is no such number r.

Input: The first line of input contains three integers A, B and n (1 ≤ A, B ≤ 106, 1 ≤ n ≤ 105).Next n lines contain information about queries. i-th line contains integers l, t, m (1 ≤ l, t, m ≤ 106) for i-th query.

Output: For each query, print its answer in a single line.


Sample Inputs:
2 1 4
1 5 3
3 3 10
7 10 2
6 4 8

1 5 2
1 5 10
2 7 4

Sample Outputs:
4
-1
8
-1

1
2

Solution (Python):
f = lambda : map(int, input().split())
(A, B, n) = f()
k = 0.5
for i in range(n):
    (l, t, m) = f()
    b = A / B + l - k
    c = b - k - m * t / B
    r = min(l + int((b * b - 2 * c) ** k - b), (t - A) // B + 1)
    print(-1 if r < l else r)

Solution (Python):
from math import *
inp = input()
(a, b, c) = inp.split()
a = float(a)
b = float(b)
c = float(c)
for i in range(0, int(c)):
    (l, t, m) = input().split()
    l = float(l)
    t = float(t)
    m = float(m)
    hl = a + (l - 1.0) * b
    if hl > t:
        print(-1)
        continue
    num = (t - hl) / b + 1.0
    terms = floor(num)
    num = (b - 2.0 * hl + sqrt((2.0 * hl - b) * (2.0 * hl - b) - 4.0 * b * (-2.0 * t * m))) / (2.0 * b)
    terms2 = floor(num)
    print(int(l + min(terms, terms2) - 1))

Solution (Python):
f = lambda : map(int, input().split())
(A, B, n) = f()
k = 0.5
for i in range(n):
    (l, t, m) = f()
    b = A / B + l - k
    c = b - k - m * t / B
    r = min(l + int((b * b - 2 * c) ** k - b), (t - A) // B + 1)
    print(-1 if r < l else r)