Soldier Kills (iii) time limit:MS | Memory limit:65535 KB Difficulty:5
-
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
-
17
RMQ algorithm Detailed
#include <stdio.h> #include <string.h> #include <vector> #include <map> #include <queue># include<stack> #include <cstdio> #include <string> #include <math.h> #include <algorithm > #define LL Long long#define PI atan (1.0) *4#define DD double#define MAX 100100#define mod 10003#define INF 0x3f3f3f3fus ing namespace std;int a[max];int n,m;int amax[max][50],amin[max][50];void RMQ () {int i,j;for (i=1;i<=n;i++) Amax[i][0 ]=amin[i][0]=a[i];for (j=1; (1<<j) <=n;j++) {for (i=1;i+ (1<<j) -1<=n;i++) {Amin[i][j] = min (Amin[i][ J-1], Amin[i + (1<< (j-1))][j-1]); AMAX[I][J] = max (amax[i][j-1], Amax[i + (1<< (j-1))][j-1]);}}} int find (int l,int r) {int K=0;while (1<< (k+1) <=r-l+1) K++;return Max (amax[l][k],amax[r-(1<<k) +1][k])- Min (amin[l][k],amin[r-(1<<k) +1][k]);} int main () {int j,i,t,k,a,b;while (scanf ("%d%d", &n,&m)!=eof) {for (i=1;i<=n;i++) scanf ("%d", &a[i]); RMQ (); while (m--) {scanf ("%d%d",&A,&B);p rintf ("%d\n", find (b));}} return 0;}
Nyoj 119 soldier Kills (iii) (RMQ)