# Office Keys

## 题目描述

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.

## 代码1

#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int n, k, p, ans = 2e9, a[1001], b[2001];
int get_dist(int x, int y) { return abs(a[x] - b[y]) + abs(b[y] - p); }
int main()
{
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;
return 0;
}


## 代码2

#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
int n, k, p, a[1001], b[2001], f[1001][2001];
int get_dist(int x, int y) { return abs(a[x] - b[y]) + abs(b[y] - p); }
int main()
{
cin >> n >> k >> p; memset(f, 0x7f, sizeof(f));
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 = 0; i <= k; ++i) f[0][i] = 0;
for (int i = 1; i <= n; ++i)
for (int j = i; j <= k; ++j)
f[i][j] = min(f[i][j - 1], max(f[i - 1][j - 1], get_dist(i, j)));
cout << f[n][k] << endl;
return 0;
}


418 I'm a teapot