Question description
There are classes in the ABC competitive programming school, and class number () targets students with a rating of .
Now, students are about to join this school. The rating of student number () is . 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 and their own rating , that is, .
For , find the minimum dissatisfaction that can be considered for student number . It is allowed to have classes with no students or classes with multiple students.
Constraints
- All input values are integers
Input
The input is given in the following format:
Output
For each , output the answer on a separate line, for a total of 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
- Sort the array in increasing order.
- For each , use the binary search method to find an index such that is minimized for all , where .
Complexity Analysis
- time complexity :
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)