CodeForces - 2093G

· · 题解

CodeForces - 2093G Shorten the Array

题意

定义长度为 m 的数组 b 的"美丽值"为所有可能数对

当满足 $f(b) \ge k$ 条件时,我们称数组 $b$ 是美丽的。 每次从 $a$ 中截出 $l$ 到 $r$ 的子数组,找出数组 $a$ 中最短的美丽子数组长度。如果不存在美丽子数组,则输出 $-1$。 ## 思路 对于这种区间问题,我们可以用双指针,固定左端点,移动右端点。 当 $\left[l, r\right]$ 满足要求时,$\left[l, r + 1\right],\left[l, r + 2\right] \cdots \left[l, n\right]$ 一定满足要求,所以我们找出每个 $l$ 的最小的 $r$,统计答案。 可以用字典树查找最小值。 ## 代码 ~~~Cpp #include <bits/stdc++.h> #define ll long long using namespace std; ll read(){ ll x = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-'){ f = -1; } ch = getchar(); } while(ch >= '0' && ch <= '9'){ x = x * 10 + ch - '0', ch = getchar(); } return x * f; } void write(ll x) { if(x < 0){ putchar('-'), x = -x; } if(x > 9){ write(x / 10); } putchar(x % 10 + '0'); } const int N = 2e5 + 3; int q, n, k; int a[N], ans; int t[N * 31][2], tc; int c[N * 31]; void change(int x, int s){ int p = 0; for(int i = 31; i >= 0; i --){ int w = (x >> i) & 1; if(!t[p][w]) t[p][w] = ++ tc; p = t[p][w]; c[p] += s; } } int Find(int x){ int p = 0, ans = 0; for(int i = 31; i >= 0; i --){ int w = (x >> i) & 1; if(!t[p][w ^ 1] || !c[t[p][w ^ 1]]) p = t[p][w]; else p = t[p][w ^ 1], ans |= (1 << i); } return ans; } int main(){ q = read(); while(q --){ for(int i = 0; i <= tc; i ++){ t[i][0] = t[i][1] = c[i] = 0; } tc = 0; ans = 1e9; n = read(), k = read(); for(int i = 1; i <= n; i ++){ a[i] = read(); } for(int l = 1, r = 0; l <= n; l ++){ while(r < l){ r ++; change(a[r], 1); } while(Find(a[r]) < k && r < n){ r ++; change(a[r], 1); } if(Find(a[r]) < k) continue; ans = min(ans, r - l + 1); change(a[l], -1); } if(ans == 1e9) cout << "-1\n"; else write(ans), putchar('\n'); } return 0; } ~~~