Skip to main content

[Atcoder typical 90] Day 7 - Smallest Subsequence

· 2 min read
Clover

Question description

There are NN classes in the ABC competitive programming school, and class number ii (1iN1 \leq i \leq N) targets students with a rating of AiA_i.

Now, QQ students are about to join this school. The rating of student number jj (1jQ1 \leq j \leq Q) is BjB_j. Each student will be dissatisfied if they go to a class that does not match their level. The dissatisfaction for each student is defined as follows:

The absolute difference between the target rating aa and their own rating bb, that is, ab|a - b|.

For j=1,2,3,,Qj = 1, 2, 3, \dots, Q, find the minimum dissatisfaction that can be considered for student number jj. It is allowed to have classes with no students or classes with multiple students.

Constraints

  • 1N300,0001 \leq N \leq 300,000
  • 1Q300,0001 \leq Q \leq 300,000
  • 0Ai1090 \leq A_i \leq 10^9
  • 0Bj1090 \leq B_j \leq 10^9
  • All input values are integers

Input

The input is given in the following format:

NN
A1 A2 A3  ANA_1\ A_2\ A_3\ \dots\ A_N
QQ
B1B_1
B2B_2
B3B_3
\dots
BQB_Q

Output

For each j=1,2,3,,Qj = 1, 2, 3, \dots, Q, output the answer on a separate line, for a total of QQ lines.

Examples Input example

4
4000 4400 5000 3200
3
3312
2992
4229
atcoder

Output example

112
208
171

In this example, we can obtain the string "acd" by taking only the 1st, 3rd, and 5th characters.
This string is the lexicographically smallest 3-character substring among all possible substrings.

Approach

  1. Sort the array AA in increasing order.
  2. For each BjB_j, use the binary search method to find an index ii such that BjAi|B_j - A_i| is minimized for all AkAA_k \in A, where {k1kQ and ki}\{k | 1 \leq k \leq Q \text{ and } k \neq i\}.

Complexity Analysis

  • time complexity : O(NlogN+QlogN)O(N\log{N} + Qlog{N})

Solution

#include <iostream>

using namespace std;

int main(){
int N;
cin >> N;
vector<int> A(N);
for (int i = 0; i < N; i++) {
cin >> A[i];
}
sort(A.begin(), A.end());
int Q;
cin >> Q;
for (int i = 0; i < Q; i++) {
int b;
cin >> b;
int p = lower_bound(A.begin(), A.end(), b) - A.begin();
if (p == 0) {
cout << abs(b - A[p]) << endl;
} else if (p == A.size()) {
cout << abs(b - A[p - 1]) << endl;
} else {
cout << min(abs(b - A[p]), abs(b - A[p - 1])) << endl;
}
}
return 0;
}

Reference

[1] 競プロ典型 90 問
[2] 007 - CP Classes(★3)

Loading Comments...