题解:P11798 【MX-X9-T2】『GROI-R3』XOR

· · 题解

思路

容易发现,记 f(n)=\bigoplus_{i=0}^ni,有:

f(n)=\begin{cases}n,&n\bmod 4=0\\1,&n\bmod 4=1\\n+1,&n\bmod 4=2\\0,&n\bmod 4=3\end{cases}

用归纳法也容易证明。

于是不妨记 x'=x\oplus f(k-1),问题变成求 f(n)=x'。简单分讨即可。

代码

#include <bits/stdc++.h>

using namespace std;

int main(){
    int T;
    scanf("%d", &T);
    while(T --){
        int l, r, k, x;
        scanf("%d %d %d %d", &l, &r, &k, &x);
        k --;
        if(k % 4 == 1) k = 1;
        else if(k % 4 == 2) k ++;
        else if(k % 4 == 3) k = 0;
        x ^= k;
        if(x % 4 == 0 && l <= x && x <= r) printf("%d\n", x);
        else if((x - 1) % 4 == 2 && l <= x - 1 && x - 1 <= r) printf("%d\n", x - 1);
        else if(x == 1){
            int a = l + 1 - (l % 4);
            if(a < l) a += 4;
            if(a <= r) printf("%d\n", a);
            else printf("-1\n");
        }else if(x == 0){
            int a = l + 3 - (l % 4);
            if(a <= r) printf("%d\n", a);
            else printf("-1\n");
        }else printf("-1\n");
    }
    return 0;
}