跳到正文

题解

CodeForces - 2093G

Chthohepta约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年7月24日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 4 分钟
获赞
1
题目
CF2093G

版本

  1. v1当前

CodeForces - 2093G Shorten the Array

题意

定义长度为 mm 的数组 bb 的”美丽值”为所有可能数对 1≤i≤j≤n1 \le i \le j \le n 中 max⁡(bi⊕bj)\max(b_i \oplus b_j) 的值。我们将数组 bb 的美丽值记为 f(b)f(b)。

当满足 f(b)≥kf(b) \ge k 条件时,我们称数组 bb 是美丽的。

每次从 aa 中截出 ll 到 rr 的子数组,找出数组 aa 中最短的美丽子数组长度。如果不存在美丽子数组,则输出 −1-1。

思路

对于这种区间问题,我们可以用双指针,固定左端点,移动右端点。

当 [l,r]\left[l, r\right] 满足要求时,[l,r+1],[l,r+2]⋯[l,n]\left[l, r + 1\right],\left[l, r + 2\right] \cdots \left[l, n\right] 一定满足要求,所以我们找出每个 ll 的最小的 rr,统计答案。

可以用字典树查找最小值。

代码

C++
#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;
}
原文