- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMosAlgorithm2.java
More file actions
Latest commit
79 lines (75 loc) · 2.12 KB
/
Copy pathMosAlgorithm2.java
File metadata and controls
79 lines (75 loc) · 2.12 KB
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
packageData_Structures;
importjava.util.*;
// Solution of http://www.spoj.com/problems/DQUERY/en/
publicclassMosAlgorithm2 {
staticintsolveSlow(int[] cnt, int[] a, inthaveLeft, inthaveRight, intneedLeft, intneedRight) {
intres = 0;
for (inti = haveRight + 1; i <= needRight; ++i) {
res += cnt[a[i]] == 0 ? 1 : 0;
++cnt[a[i]];
}
for (inti = haveLeft; i < needLeft; ++i) {
res += cnt[a[i]] == 1 ? -1 : 0;
--cnt[a[i]];
}
for (inti = haveRight + 1; i <= needRight; ++i) {
--cnt[a[i]];
}
for (inti = haveLeft; i < needLeft; ++i) {
++cnt[a[i]];
}
returnres;
}
staticint[] solve(int[] a, int[][] queries) {
intn = a.length;
Map<Integer, Integer> m = newHashMap<>();
intid = 0;
for (inti = 0; i < n; i++) {
if (!m.containsKey(a[i]))
m.put(a[i], id++);
a[i] = m.get(a[i]);
}
intblockSize = (int) Math.sqrt(n);
intblocks = (n + blockSize - 1) / blockSize;
int[][] head = newint[blocks][blocks];
for (inti = 0; i < blocks; i++)
Arrays.fill(head[i], -1);
intq = queries.length;
int[] left = newint[q];
int[] right = newint[q];
int[] next = newint[q];
for (inti = 0; i < q; i++) {
left[i] = queries[i][0];
right[i] = queries[i][1];
intlb = left[i] / blockSize;
intrb = right[i] / blockSize;
next[i] = head[lb][rb];
head[lb][rb] = i;
}
int[] res = newint[q];
for (intleftBlock = 0; leftBlock < blocks; leftBlock++) {
int[] cnt = newint[id];
intcurAnswer = 0;
for (intrightBlock = leftBlock; rightBlock < blocks; rightBlock++) {
for (inti = head[leftBlock][rightBlock]; i >= 0; i = next[i]) {
res[i] = curAnswer
+ solveSlow(cnt, a, leftBlock * blockSize, rightBlock * blockSize - 1, left[i], right[i]);
}
if (rightBlock + 1 < blocks) {
for (inti = 0; i < blockSize; i++) {
intcur = a[rightBlock * blockSize + i];
curAnswer += cnt[cur] == 0 ? 1 : 0;
++cnt[cur];
}
}
}
}
returnres;
}
publicstaticvoidmain(String[] args) {
int[] a = {1, 2, 3, 4};
int[][] queries = {{3, 3}};
int[] res = solve(a, queries);
System.out.println(Arrays.toString(res));
}
}