Softeer 6247번
https://softeer.ai/practice/6246/history?questionType=ALGORITHM
import java.io.*;
import java.util.*;
public class Main {
// input
private static BufferedReader br;
// variables
private static int N, Q;
private static int[] arr;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
input();
bw.write(solve());
bw.close();
} // End of main()
private static String solve() throws IOException {
StringBuilder sb = new StringBuilder();
// 이분 탐색
for(int i=0; i<Q; i++) {
int target = Integer.parseInt(br.readLine());
int ret = binarySearch(0, N - 1, target);
if(ret == -1) {
sb.append(0);
} else {
sb.append(ret * ((N - 1) - ret) );
}
sb.append('\n');
}
return sb.toString();
} // End of solve()
private static int binarySearch(int low, int high, int target) {
if (low > high) {
return -1;
}
int mid = (low + high) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] > target) {
return binarySearch(low, mid - 1, target);
} else {
return binarySearch(mid + 1, high, target);
}
} // End of binarySearch()
private static void input() throws IOException {
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
Q = Integer.parseInt(st.nextToken());
arr = new int[N];
st = new StringTokenizer(br.readLine());
for(int i=0; i<N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(arr);
} // End of input()
} // End of Main class