"RMQ algorithm": Used for the maximum (minimum) value of the query interval when the array is too large.
Time complexity: O (NLOGN), the main time of the payment on the preprocessing, query as long as O (1).
-
Describe
-
South General Command of N Soldiers, soldiers are numbered 1~n, South general often love to take a certain number of the highest number of kills and kill the lowest number of people to compare, calculated two people's kill number difference, with this method on the one hand can be encouraged to kill the high number of people, on the other hand is criticized as the low number of people, played a very good
Therefore, the South General often asked the military adviser I soldier to the No. J Soldier, the highest number of kills and the lowest number of people to kill the military exploit difference between the value of what.
Now, please write a program, help the handyman to answer every time the South General's inquiry.
Note that the South General may inquire many times.
-
Input
-
Only one set of test data
The first line is a two integer n,q, where n represents the total number of soldiers. Q indicates the number of times the South General inquired. (1<n<=100000,1<q<=1000000)
The following line has n integer Vi (0<=vi<100000000), each of which represents the number of kills per person.
After the Q line, there are two positive positive m,n per line, indicating that the South general is inquiring about the number M to Soldier No. N.
-
Output
-
For each query, output the difference between the maximum and minimum number of soldiers killed by a soldier of number m to the nth soldier.
-
Sample input
-
5 21 2 6 9 31 22 4
-
Sample output
-
1
-
7
-
The code is as follows: (when the data is too large, it is recommended to use scanf input, with CIN may be time overrun).
#include <cstdio>#include<algorithm>#include<cmath>using namespacestd;Const intN =100010;intmaxsum[ -][n], minsum[ -][n]; voidRMQ (intNum//pretreatment->o (NLOGN){ for(inti =1; I! = -; ++i) for(intj =1; J <= Num; ++j)if(J + (1<< i)-1<=num) {Maxsum[i][j]= Max (Maxsum[i-1][J], Maxsum[i-1][j + (1<< I >>1)]); MINSUM[I][J]= Min (Minsum[i-1][J], Minsum[i-1][j + (1<< I >>1)]); }}intMain () {intnum, query; intsrc, des; scanf ("%d%d", &num, &query); for(inti =1; I <= num; ++i)//Input Information Processing{scanf ("%d", &maxsum[0][i]); minsum[0][i] = maxsum[0][i]; } RMQ (num); while(query--)//O (1) Query{scanf ("%d%d", &SRC, &des); intK = (int) (Log (des-src +1.0)/log (2.0)); intMaxres = Max (Maxsum[k][src], Maxsum[k][des-(1<< k) +1]); intminres = min (minsum[k][src], Minsum[k][des-(1<< k) +1]); printf ("%d\n", Maxres-minres); } return 0;}
ACM Topic ———— Soldier Kills (iii)