Codeforces Round #424 (Div. 2) D. Office Keys(贪心 二分 or DP)

时间:2021-07-28 18:59:06

题意:有n个人和k把钥匙(n<=1000, k<=2000, k>=n),n个人都必须拿一把钥匙去p点,一把钥匙不能多人拿。问最后每个人都到达p点最少需要多少时间。


思路:对人和钥匙都排序一下,然后有三种做法:


1.二分答案 贪心验证:左边的人取的钥匙越靠左 对右边的人的影响越小, 所以每次尽量取左边的钥匙


2.DP:转移方程:dp[i][j] = min(dp[i][j-1], max(dp[i-1][j-1], abs(a[i]-b[j])+abs(b[j]-p)))


3.贪心可以得到结论,取得n把钥匙一定是连续的,所以枚举连续的长度为n的区间,第一个人取该区间第一把钥匙,第二个取第二把...


二分代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2005;
ll a[maxn], b[maxn], n, k, p;

bool judge(ll x)
{
int setp = 1;
for(int i = 1; i <= n; i++)
{
while(setp <= k && abs(a[i]-b[setp])+abs(b[setp]-p) > x) setp++;
if(setp > k) return 0;
setp++;
}
return 1;
}

int main(void)
{
while(cin >> n >> k >> p)
{
for(int i = 1; i <= n; i++)
scanf("%I64d", &a[i]);
for(int i = 1; i <= k; i++)
scanf("%I64d", &b[i]);
sort(a+1, a+1+n);
sort(b+1, b+1+k);
ll ans, l = 0, r = 0x3f3f3f3f3f3f3f3f;
while(l <= r)
{
ll mid = (l+r)/2;
// cout << l << ' ' << r << endl;
if(judge(mid)) ans = mid, r = mid-1;
else l = mid+1;
}
printf("%I64d\n", ans);
}
return 0;
}



2.DP代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2005;
ll a[maxn], b[maxn], n, k, p;
ll dp[maxn][maxn];

int main(void)
{
while(cin >> n >> k >> p)
{
for(int i = 1; i <= n; i++)
scanf("%I64d", &a[i]);
for(int i = 1; i <= k; i++)
scanf("%I64d", &b[i]);
sort(a+1, a+1+n);
sort(b+1, b+1+k);
dp[0][0] = 0;
for(int i = 1; i <= n; i++)
for(int j = i; j <= k; j++)
{
if(i == j)
dp[i][j] = max(dp[i-1][j-1], abs(a[i]-b[j])+abs(b[j]-p));
else
dp[i][j] = min(dp[i][j-1], max(dp[i-1][j-1], abs(a[i]-b[j])+abs(b[j]-p)));
}
printf("%I64d\n", dp[n][k]);
}
return 0;
}