import
java.util.ArrayList;
import
java.util.List;
public
class
Main {
static
ArrayList<Long> collectMaximumOranges(
int
n,
int
q, ArrayList<ArrayList<Integer>> trees,
ArrayList<ArrayList<Integer>> queries) {
int
i =
0
;
long
maxx = Long.MIN_VALUE;
long
minn = Long.MAX_VALUE;
while
(i < n) {
long
loc = trees.get(i).get(
0
);
long
oranges = trees.get(i).get(
1
);
maxx = Math.max(maxx, loc);
minn = Math.min(minn, loc);
i++;
}
i =
0
;
long
[] v =
new
long
[(
int
) (maxx +
1
)];
while
(i < n) {
long
loc = trees.get(i).get(
0
);
long
oranges = trees.get(i).get(
1
);
v[(
int
) loc] = oranges;
i++;
}
i = (
int
) minn +
1
;
while
(i <= maxx) {
v[i] = v[i] + v[i -
1
];
i++;
}
i =
0
;
ArrayList<Long> res =
new
ArrayList<>();
while
(i < q) {
long
start = queries.get(i).get(
0
);
long
end = queries.get(i).get(
1
);
long
left =
0
;
long
right =
0
;
if
(start > maxx) {
left = v[(
int
) maxx];
}
else
if
(start -
1
>=
0
) {
left = v[(
int
) (start -
1
)];
}
if
(end > maxx) {
right = v[(
int
) maxx];
}
else
if
(end <
0
) {
right =
0
;
}
else
{
right = v[(
int
) end];
}
res.add(right - left);
i++;
}
return
res;
}
public
static
void
main(String[] args) {
int
n =
5
;
int
q =
3
;
ArrayList<ArrayList<Integer>> trees =
new
ArrayList<>();
trees.add(
new
ArrayList<>(List.of(
1
,
2
)));
trees.add(
new
ArrayList<>(List.of(
3
,
2
)));
trees.add(
new
ArrayList<>(List.of(
4
,
5
)));
trees.add(
new
ArrayList<>(List.of(
7
,
1
)));
trees.add(
new
ArrayList<>(List.of(
10
,
4
)));
ArrayList<ArrayList<Integer>> queries =
new
ArrayList<>();
queries.add(
new
ArrayList<>(List.of(
0
,
12
)));
queries.add(
new
ArrayList<>(List.of(
4
,
6
)));
queries.add(
new
ArrayList<>(List.of(
2
,
8
)));
ArrayList<Long> res = collectMaximumOranges(n, q, trees, queries);
for
(
long
a : res) {
System.out.print(a +
" "
);
}
}
}