-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbaekjoon_31965.java
More file actions
85 lines (67 loc) · 2.95 KB
/
baekjoon_31965.java
File metadata and controls
85 lines (67 loc) · 2.95 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
80
81
82
83
84
85
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class baekjoon_31965 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int houseCount = Integer.parseInt(st.nextToken());
int queryCount = Integer.parseInt(st.nextToken());
long[] positions = new long[houseCount];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < houseCount; i++) {
positions[i] = Long.parseLong(st.nextToken());
}
long[] prefixSum = new long[houseCount + 1];
for (int i = 1; i <= houseCount; i++) {
prefixSum[i] = prefixSum[i - 1] + positions[i - 1];
}
StringBuilder output = new StringBuilder();
for (int q = 0; q < queryCount; q++) {
st = new StringTokenizer(br.readLine());
long leftValue = Long.parseLong(st.nextToken());
long rightValue = Long.parseLong(st.nextToken());
int leftIdx = lowerBound(positions, leftValue);
int rightIdx = upperBound(positions, rightValue) - 1;
if (leftIdx > rightIdx || leftIdx == rightIdx) {
output.append("0\n");
continue;
}
long costLeft = calculateCost(leftIdx, leftIdx, rightIdx, positions, prefixSum);
long costRight = calculateCost(rightIdx, leftIdx, rightIdx, positions, prefixSum);
long maxCost = Math.max(costLeft, costRight);
int medianIdx = (leftIdx + rightIdx) / 2;
long minCost = calculateCost(medianIdx, leftIdx, rightIdx, positions, prefixSum);
output.append(maxCost - minCost).append('\n');
}
System.out.print(output);
}
static int lowerBound(long[] arr, long target) {
int left = 0, right = arr.length;
while (left < right) {
int mid = (left + right) / 2;
if (arr[mid] < target) left = mid + 1;
else right = mid;
}
return left;
}
static int upperBound(long[] arr, long target) {
int left = 0, right = arr.length;
while (left < right) {
int mid = (left + right) / 2;
if (arr[mid] <= target) left = mid + 1;
else right = mid;
}
return left;
}
static long calculateCost(int centerIdx, int leftIdx, int rightIdx, long[] pos, long[] prefixSum) {
long leftCount = centerIdx - leftIdx;
long leftSum = prefixSum[centerIdx] - prefixSum[leftIdx];
long leftCost = leftCount * pos[centerIdx] - leftSum;
long rightCount = rightIdx - centerIdx;
long rightSum = prefixSum[rightIdx + 1] - prefixSum[centerIdx + 1];
long rightCost = rightSum - rightCount * pos[centerIdx];
return leftCost + rightCost;
}
}