Solar Flight

For a line segment query, find the maximum total intercept-weight above a given ray over all x in a length-K window.

Hard8GeometrySortingBinary searchPrefix sumNo attempts yetTime limit15sMemory limit512 MB

Problem

A new era of aviation has arrived: the first solar-powered jumbo jets are about to open for public travel. The sunlight that powers these planes can be blocked by other objects in the sky, which raises some safety concerns. So some statistics about the planned initial flights must be calculated first.

Consider NN flight paths, all travelling east from one city to another. Treat each plane as a single point. Model the sky as a Cartesian plane, where the x-coordinate is the distance east of an arbitrary fixed point and the y-coordinate is the altitude. Only the part of the sky with x-coordinates in the closed range [0,X][0, X] matters, and every flight path is a straight line there. Plane ii flies from (0,Ai)(0, A_i) to (X,Bi)(X, B_i). All AA values are distinct, and all BB values are distinct. The planes travel along their paths at unknown, possibly non-constant speeds, so at any moment a plane can be anywhere along its path. The planes never crash into each other, though: if two flight paths cross, the two planes do not reach the intersection point at exactly the same time.

Each plane ii has an interference factor CiC_i, which measures how much plane ii reduces the solar absorbing capability of any plane below it.

The solar panels on each plane are unusual: they collect energy only from directly above the plane. So the sunlight a plane absorbs can be blocked by other planes that are at the same x-coordinate and have a larger y-coordinate. The amount by which its panels are obstructed is the sum of the interference factors of all such planes.

Given a fixed distance constant KK, answer QQ queries. Query ii asks for the largest possible amount by which the solar panels of plane PiP_i could be obstructed at a single moment, at any point while the x-coordinate of plane PiP_i is in the closed range [Si,Si+K][S_i, S_i + K].

Input

The first line contains four space-separated integers XX, KK, NN, and QQ: XX (1X1091 \le X \le 10^9) is the maximum x-coordinate to consider, KK (1KX1 \le K \le X) is the fixed distance constant, NN (1N20001 \le N \le 2000) is the number of flight paths, and QQ (1Q8000001 \le Q \le 800000) is the number of queries.

Line ii of the next NN lines contains three integers AiA_i, BiB_i, and CiC_i (1Ai,Bi,Ci1091 \le A_i, B_i, C_i \le 10^9): the starting y-coordinate, the ending y-coordinate, and the interference factor of plane ii.

Line ii of the next QQ lines contains two integers PiP_i and SiS_i (1PiN1 \le P_i \le N, 0SiXK0 \le S_i \le X - K), a query about plane PiP_i while its x-coordinate is in the range [Si,Si+K][S_i, S_i + K].

Output

Print QQ lines. Line ii contains the integer answer to query ii.