跳到正文

题解

题解:CF1682B AND Sorting

appear_bug约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年10月19日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 3 分钟
题目
CF1682B

版本

  1. v1当前

Solution

与运算练习好题,本题解中 and⁡\operatorname{and} 即为按位与。

在此之前,我们先不加证明地给出两个结论,请读者自行上某度或独立证明:

  1. xand⁡y=yand⁡xx \operatorname{and} y = y \operatorname{and} x
  2. xand⁡−1=xx \operatorname{and} -1 = x(−1-1 的二进制位全为 11)

我们发现,在题目要求下,只有 pi≠ip_i \neq i 时 pip_i 才需要进行交换,那么我们只需要处理这些位置上的元素。

本题中我们要找的 xx 值就是让全部不在对应位置上的值相与。由上方结论一可知,我们不必关心运算顺序,因为它满足交换律。为了避免多于判断,使用性质二,令 ans=−1ans=-1,遍历一遍数组,如果满足 pi≠ip_i \neq i,就执行一次 ans←ansand⁡pians \gets ans \operatorname{and} p_i。最后的 ansans 值即为题中要找的 xx。

保证 ∀i,j∈[0,n),piand⁡pj≥x\forall i,j \in [0,n),p_i \operatorname{and} p_j \geq x,虽然题目上要求 piand⁡pj=xp_i \operatorname{and} p_j = x 时才可交换,但会存在一个中间变量 cc 使得他们可以交换,证明:

  • piand⁡pj=xp_i \operatorname{and} p_j = x 时,直接进行交换。

  • piand⁡pj>xp_i \operatorname{and} p_j > x 时,说明 pip_i 和 pjp_j 一定存在某位二进制位上是 11,但在 xx 中此位为 00,由于 xx 是全体满足 pi≠ip_i \neq i 的 pip_i 的按位与值,我们要找到一个中间值 cc 使得 piand⁡c=xp_i \operatorname{and} c = x 且 pjand⁡c=xp_j \operatorname{and} c = x,取 c=xc = x,因为 piand⁡pj>xp_i \operatorname{and} p_j > x,所以 xx 中包含了全部的 11 位,因此 piand⁡x=xp_i \operatorname{and} x = x,同理可得 pjand⁡x=xp_j \operatorname{and} x = x,故一定存在一个 cc 使得这两个值得以进行了交换。

证毕。

Code

注:据上述分析,我们没有必要开数组记录或保存值,pip_i 可用一个 pp 来读入,空间复杂度由 O(n)O(n) 降至 O(1)O(1)。我的代码之中使用的 xx 与题中 xx 意义不同,注意进行辨别。

时间复杂度为 O(∑n)O(\sum n),在可接受范围之内。

附上通过记录

C++
int n,x;//代码很短,就是证明比较麻烦
int solve(){
    int ans=-1;//为什么用-1?见结论2
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&x);
        if(x!=i) ans&=x;//不在自己的位上,进行一次与运算
    }
    printf("%d\n",ans);//这就愉快地通过啦^_^
    return 0;
}
原文