how the function sort is working in the mo's algorithim in following code

using namespace std;

#define N 311111
#define A 1111111
#define BLOCK 555 // ~sqrt(N)

int cnt[A], a[N], ans[N], answer = 0;

struct node {
	int L, R, i;

bool cmp(node x, node y) {
	if(x.L/BLOCK != y.L/BLOCK) {
		// different blocks, so sort by block.
		return x.L/BLOCK < y.L/BLOCK;
	// same block, so sort by R value
	return x.R < y.R;

void add(int position) {
	if(cnt[a[position]] == 1) {

void remove(int position) {
	if(cnt[a[position]] == 0) {

int main() {
	int n;
	scanf("%d", &n);
	for(int i=0; i<n; i++)
		scanf("%d", &a[i]);

	int m;
	scanf("%d", &m);
	for(int i=0; i<m; i++) {
		scanf("%d%d", &q[i].L, &q[i].R);
		q[i].L; q[i].R;
		q[i].i = i;

	sort(q, q + m, cmp);

	int currentL = 0, currentR = 0;
	for(int i=0; i<m; i++) {
		int L = q[i].L, R = q[i].R;
		while(currentL < L) {
		while(currentL > L) {
		while(currentR <= R) {
		while(currentR > R+1) {
		ans[q[i].i] = answer;

	for(int i=0; i<m; i++)
		printf("%d\n", ans[i]);  
1 Like

someone pls explain the working of sort in the mo’s algorithm @vijju123

question of spoj //

finally got understood it is sorting structure with respect to value of L and if value of L is same then we sort with less value of R

There is a even better optimization to this standard algo, which @meooow discussed in some deep and dark depths of this forum. Feeling up for a hunt? :stuck_out_tongue:


I call it @meooow’s Algorithm :stuck_out_tongue:

1 Like

thank u so much

i would be glad if u let me k ow what is difference bw mo’s algo and sqareroot decomposition @vijju123 @dishant_18

Mo’s decomposition is a specialized type of square decomposition to use when all queries are available before hand, and when the question satisfies Mo’s conditions.

1 Like

In addition to what @vijju123 said, Mo’s algorithm can only be used when there are no updates involved. Also, Mo’s algorithm is an offline algorithm whereas squareroot decomposition is an online algorithm!