CF_2106_D. Flower Boy
题目链接:Problem - D - Codeforces
题目大意:
要在大小为 n 的 数组 中 从左到右 选取 个数
使得选出来的数大于等于 数组中对应位置上的数
有可能不够选,因此可以将一个任意大小的数 插入到 数组中的任意位置,注意该操作只能执行一次
求: 最小是多少。如果可以不用插入,则输出 。如果插入了也无法选出 个数,则输出 。
贪心:
贪心思路,只要当前数字大于等于 数组上对应位置的数字,就选取;
使用魔法棒培育一朵美丽值为 的新花, 说明这朵花一定可以满足某个位置上要求的美丽值
换个角度,可以看成是跳过这个美丽值,也可以看成是删除某一个数的问题
从左往右遍历维护 pre 数组存储在每个位置能最多选取多少数字
从右往左遍历维护 suf 数组存储在倒过来的情况下每个位置最多选取多少数字
当 从左边开始最多能选取的数字 + 从右边开始最多能选的数字 == k - 1 时,
即 pre[i] + suf[i+1] == m - 1,说明在b数组中的 pre[i] + 1 这个位置可以被删掉,
上述式子中的 pre[i] 代表选的是1 ~ i 的数,suf[i+1] 表示 选的是 i+1 ~ n 的数
遍历1~n,取最小值即可
若pre[n]==m,说明不用删除也能满足要求,输出-1即可
代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
#include<tuple>
#define inf 72340172838076673
#define int long long
#define endl '\n'
#define F first
#define S second
#define mst(a,x) memset(a,x,sizeof (a))
using namespace std;
typedef pair<int, int> pii;
const int N = 200086, mod = 998244353;
int n, m;
int a[N], b[N];
int pre[N], suf[N];
int res = 0;
void solve() {
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= m; i++) cin >> b[i];
int l = 1;
for (int i = 1; i <= n; i++) {
pre[i] = pre[i - 1];
if (l <= m && a[i] >= b[l]) {
l++;
pre[i]++;
}
}
int r = m;
suf[n + 1] = 0;
for (int i = n; i; i--) {
suf[i] = suf[i + 1];
if (r >= 1 && a[i] >= b[r]) {
r--;
suf[i]++;
}
}
if (pre[n] == m) cout << 0 << endl;
else {
int res = inf;
int mx = 0;
for (int i = 0; i <= n; i++) {
if (pre[i] + suf[i + 1] == m - 1) {
res = min(res, b[pre[i] + 1]);
}
}
if (res > inf / 2) cout << -1 << endl;
else cout << res << endl;
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int T = 1;
cin >> T;
while (T--) solve();
return 0;
}

浙公网安备 33010602011771号