There are $n$ people and $k$ keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn’t be taken by anybody else.
You are to determine the minimum time needed for all $n$ people to get to the office with keys. Assume that people move a unit distance per $1$ second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it.
#include<iostream> #include<cmath> #include<algorithm> usingnamespace std; int n, k, p, ans = 2e9, a[1001], b[2001]; intget_dist(int x, int y){ returnabs(a[x] - b[y]) + abs(b[y] - p); } intmain() { cin >> n >> k >> p; for (int i = 1; i <= n; ++i) cin >> a[i]; for (int i = 1; i <= k; ++i) cin >> b[i]; sort(a + 1, a + n + 1), sort(b + 1, b + k + 1); for (int i = 1; i <= k - n + 1; ++i) { int ma = 0; for (int j = i; j <= i + n - 1; ++j) ma = max(ma, get_dist(j - i + 1, j)); ans = min(ans, ma); } cout << ans << endl; return0; }