-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mo.java
79 lines (74 loc) · 1.41 KB
/
Mo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
//Mo's Algorithm
public class Mo {
public static int b;
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int n= in.nextInt();
int q= in.nextInt();
query [] qq= new query[q];
int [] a= new int[n];
for (int i = 0; i < a.length; i++) {
a[i]= in.nextInt();
}
b= (int) Math.sqrt(n)+1;
for (int i = 0; i < q; i++) {
int l= in.nextInt()-1;
int r= in.nextInt()-1;
qq[i]= new query(l, r, i);
}
Arrays.sort(qq);
int [] f= new int[1000001];
int cl=0, cr= 0, len=0;
int [] res= new int[q];
for (int i = 0; i < q; i++) {
int l= qq[i].l;
int r= qq[i].r;
while(cl<l) {
f[a[cl]]--;
if(f[a[cl]]==0) len--;
cl++;
}
while(cl>l) {
cl--;
f[a[cl]]++;
if(f[a[cl]]==1) len++;
}
while(cr<=r) {
f[a[cr]]++;
if(f[a[cr]]==1) len++;
cr++;
}
while(cr>r+1) {
cr--;
f[a[cr]]--;
if(f[a[cr]]==0) len--;
}
res[qq[i].id]= len;
}
for(int cur : res) {
System.out.println(cur);
}
}
static class query implements Comparable <query>{
public int l, r, id;
public query(int a, int b, int c) {
l = a;
r = b;
id= c;
}
public int compareTo(query o) {
int thing= l/b;
int thing1= o.l/b;
if (thing != thing1) {
return thing-thing1;
}
if((thing&1)==1) {
return r-o.r;
}
return o.r-r;
}
}
}