思路:
问题的关键在于对钥匙按照位置排序之后,最终选择的n个钥匙一定是其中的一个连续的区间。
实现:
1 #include <iostream> 2 #include <cstdio> 3 #include <cmath> 4 #include <algorithm> 5 using namespace std; 6 typedef long long ll; 7 const ll INF = 0x3f3f3f3f3f3f3f3f; 8 ll man[1005], key[2005]; 9 ll cal(ll m, ll k, ll p) 10 { 11 if ((k >= m && k <= p) || (k <= m && k >= p)) return abs(m - p); 12 return abs(m - k) + abs(k - p); 13 } 14 int main() 15 { 16 ll n, k, p, ans = INF; 17 cin >> n >> k >> p; 18 for (int i = 0; i < n; i++) cin >> man[i]; 19 for (int i = 0; i < k; i++) cin >> key[i]; 20 sort(man, man + n); sort(key, key + k); 21 for (int i = 0; i <= k - n; i++) 22 { 23 ll maxn = 0; 24 for (int j = 0; j < n; j++) 25 { 26 maxn = max(maxn, cal(man[j], key[j + i], p)); 27 } 28 ans = min(ans, maxn); 29 } 30 cout << ans << endl; 31 return 0; 32 }