Optimizing Mo's Algorithm
문제
Juku is preparing for the Especially Important Olympiad and discovered the following problem:
Sums in an Array
You are given an array with length and queries of the form .
For each query give the result as answer.
It is known that .
Juku wrote the following pseudocode to solve the problem:
lptr = 1, rptr = 1, sum = A[1], ops = 0
for each query (ql, qr):
while rptr < qr:
rptr += 1
sum += A[rptr]
ops += 1
while lptr > ql:
lptr -= 1
sum += A[lptr]
ops += 1
while rptr > qr:
sum -= A[rptr]
rptr -= 1
ops += 1
while lptr < ql:
sum -= A[lptr]
lptr += 1
ops += 1
print sum
The running time of this code exceeded the time limit. However, Juku vaguely remembered that in some lecture someone said something about some "Mo's algorithm" and started thinking: "Could I reorder the queries such that the program would fit within time limit? Moreover, how fast could I make my program by just reordering queries?"
You're given queries of the form . Additionally, it is guaranteed that the queries are uniformly distributed (see the remark). Reorder queries such that by running the above pseudocode the final value of variable ops would be as small as possible.
입력
The first line of the input contains two space-separated integers and (). On the following input lines there are two space-separated integers ja on each ().
출력
The output should contain lines. Each line should have two space-separated integers and . The queries in the output file must be a permutation of the queries in the input file.
힌트
The actual input files have been generated using the following code:
print(100000, 100000)
for i in 1...100000:
l = random(1, 100000)
r = random(1, 100000)
if (l < r):
print(l, r)
else:
print(r, l)
Here, random(1, 100000) returns an integer such that and all possible return values are equally probable.
예제
예제 1
7 6 1 5 2 7 4 4 1 2 3 6 1 2
2 7 1 2 3 6 1 2 4 4 1 5