The MO team algorithm is an optimized brute force algorithm . The MO team algorithm is to be asked to first the left endpoint belongs to the block sort, and then by the right endpoint sort. Just know all the questions in advance. The order of each inquiry can be reasonably organized to reduce complexity.
D. Powerful array
Typical MO team algorithm problem
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <cmath>5#include <algorithm>6#include <string>7#include <vector>8#include <Set>9#include <map>Ten#include <stack> One#include <queue> A#include <sstream> -#include <iomanip> - using namespacestd; thetypedefLong LongLL; - Const intinf=0x4fffffff; - Const intexp=1e-5; - Const intms=200005; + - intA[ms]; + intcnt[5*MS]; A LL Ans[ms]; at - structnode - { - intL,r; - intno,qid; - BOOL operator< (ConstNode &a)Const in { - returnno<a.no| | (no==a.no&&r<A.R); to } + }nodes[ms]; - the * intn,size; $ LL Res;Panax Notoginseng intL,r; -LL Query (intXintYintflag) the { + if(flag) A { the for(inti=x;i<l;i++) + { -res+= (cnt[a[i]]<<1|1)*A[i]; $cnt[a[i]]++; $ } - for(inti=l;i<x;i++) - { thecnt[a[i]]--; -res-= (cnt[a[i]]<<1|1)*A[i];Wuyi } the for(inti=r+1; i<=y;i++) - { Wures+= (cnt[a[i]]<<1|1)*A[i]; -cnt[a[i]]++; About } $ for(inti=y+1; i<=r;i++) - { -cnt[a[i]]--; -res-= (cnt[a[i]]<<1|1)*A[i]; A } + } the Else - { $ for(inti=x;i<=y;i++) the { theres+= (cnt[a[i]]<<1|1)*A[i]; thecnt[a[i]]++; the } - } inL=x; R=y; the returnRes; the } About the intMain () the { the intQ; +scanf"%d%d",&n,&Q); - for(intI=1; i<=n;i++) the {Bayiscanf"%d", &a[i]);//Note that%d is much faster than%i64d. the //in large amounts of data input, you can use%d do not use%I64D, but pay attention to data overflow the } -SIZE=SQRT (n+0.5); - for(intI=0; i<q;i++) the { thescanf"%d%d",&nodes[i].l,&NODES[I].R); thenodes[i].no=nodes[i].l/SIZE; theNodes[i].qid=i; - } theSort (nodes,nodes+Q); thememset (CNT,0,sizeof(CNT)); theres=0;94 for(intI=0; i<q;i++) theans[nodes[i].qid]=query (nodes[i].l,nodes[i].r,i); the for(intI=0; i<q;i++) theprintf"%i64d\n", Ans[i]);98 return 0; About}
D. Powerful array the algorithm or block array is actually a bit of an optimization of violence