PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#BS0000307. Tavas và dãy rau cần (Tavas and Karafs)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Tavas và dãy rau cần (Tavas and Karafs)

Tavas and Karafs

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

An infinite one-based sequence has heights si=A+(i−1)Bs_i=A+(i-1)B. In query (l,t,m)(l,t,m), one bite reduces up to m distinct positive heights by one. Find the greatest r≥lr\ge l for which all plants from l through r can be consumed in at most t bites. Queries are independent.

Input

First line: A,B,qA,B,q. Each of the next q lines contains l,t,ml,t,m.

Output

For each query, print the greatest r, or -1 if none exists.

Subtasks

  • Subtask 1 (20 points): 1≤A,B,l,t,m≤301\le A,B,l,t,m\le30; 1≤q≤301\le q\le30.
  • Subtask 2 (30 points): 1≤A,B,l,t≤1061\le A,B,l,t\le10^6; m=1m=1; 1≤q≤1051\le q\le10^5.
  • Subtask 3 (50 points): 1≤A,B,l,t,m≤1061\le A,B,l,t,m\le10^6; 1≤q≤1051\le q\le10^5.

Examples

Input 1

2 1 4
1 5 3
3 3 10
7 10 2
6 4 8

Output 1

4
-1
8
-1

Explanation

First query: heights 2,3,4,5 sum to 14, within 15; the next height 6 exceeds t. Queries 2 and 4 fail at the first plant. Query 3 permits heights 8,9, but adding 10 exceeds total capacity 20.