1#include <iostream>2 using namespacestd;3#include <cstdio>4#include <cstring>5 /*6 Description:7 rmq<t> RR; A class that defines the minimum value of a query interval with a data type of T8 SETMAXN (T MAXN); Sets the maximum value of the initialized array9 creat (T a[],int MAXN) sets the array of queries, and arrays of lengths, starting from 0Ten Getx (int la,int lb) query the minimum value of the interval labeled la-lb in the array One getw (int la,int lb) to query the minimum interval of a position in an array of la-lb A custom types require overloading < - */ -template<classT> the classrmq{ - Public: -t*A; - intT; +T * *mn; - T MAXN; + int*log2; A voidSETMAXN (T *MAXN) { at This->maxn=*MAXN; - } - voidSETMAXN (T maxn) { - This->maxn=MAXN; - } - voidCreat (T a[],intMAXN) {//Establish a RMQ processing class with a maximum of MAXN in intk=1, p=0; -Log2=New int[maxn+1]; to for(intI=0; i<=maxn;i++) +Log2[i]= (i==0?-1:log2[i>>1]+1); - while(k<MAXN) { thek*=2; *p+=1; $ }Panax Notoginsengmn=Newt*[maxn+1]; - for(intI=0; i<maxn;i++){ theMn[i] =Newt[t+1]; +mn[i][0]=A[i]; A for(intj=1; j<=t;j++) themn[i][j]=MAXN; + } -t=p; $ for(intj=1; j<=t;j++) $ for(intI=0; i+ (1<<J) <= maxn;i++){ -T sa=mn[i][j-1]; -T sb=mn[i+ (1<< (J-1))][j-1]; the if(sa<SB) -mn[i][j]=sa;Wuyi Else themn[i][j]=sb; - } Wu } -T Getx (intQlintqr) { About intk=log2[qr-ql+1]; $ returnMin (mn[ql][k],mn[qr-(1<<K) +1][k]); - } -T GETW (intQlintqr) { -QL--, qr--; A intk=log2[qr-ql+1]; + returnMin (mn[ql][k],mn[qr-(1<<K) +1][k]); the } - } ; $rmq<int>RR; the inta[]={1,3,4,5,6,7,2,4,5,6,7,8}; the intMain () { theRr. SETMAXN (0x7f7f7f7f); theRr. Creat (A, A); - while(1){ in intb; thescanf"%d%d",&a,&b); theCout<<rr. GETW (b) <<Endl; About } the}
View Code
Self-written RMQ St algorithm template class