#K95887. Minimum Sum of Distances Between Pictures and Trees
Minimum Sum of Distances Between Pictures and Trees
Minimum Sum of Distances Between Pictures and Trees
You are given several test cases. In each test case, there are two sets of points on a one-dimensional line: one representing the positions of trees, and the other representing the points where photos are taken. For each photo point, you need to find the tree that is closest to it (in terms of absolute distance) and then compute the sum of these minimum distances.
Formally, for each picture point (p), you are to compute (\min_{t \in T} |p - t|), where (T) is the set of tree positions. The answer for the test case is the sum of these minimum distances. Your algorithm should be efficient (e.g. use binary search after sorting the tree positions) to handle larger inputs.
Constraints: The number of trees and picture points in each test case will be provided as input, followed by the tree positions and the picture points. It is guaranteed that the positions are integers.
inputFormat
The first line of input contains an integer (T), the number of test cases. For each test case, the input is given in three lines:
- The first line contains two integers (N) and (M) where (N) is the number of trees and (M) is the number of picture points.
- The second line contains (N) space-separated integers denoting the positions of the trees.
- The third line contains (M) space-separated integers denoting the positions where pictures are taken.
All values are given using standard input (stdin).
outputFormat
For each test case, print a single line containing one integer: the minimum sum of distances from each picture point to its nearest tree. Output the results to standard output (stdout).## sample
2
3 2
1 5 9
2 7
4 3
2 6 8 10
1 12 9
3
4
</p>