HDU 5968

题意

给出一个长为n的数组a,给出m个质询,每个质询给出一个数字,需要找到序列a中所有连续子序列的异或结果中与质询数字差的绝对值最小的一个,输出最长的这种连续子序列的长度

思路

异或前缀和+暴力
我们知道一个数异或自己即抵消异或效果
比如a^b^a = b , a^a^b = b
那么我们存下前缀和之后,想要求i~j的异或结果即pre[j]^pre[i-1]

注意: ‘^’的优先级比双目运算符‘-’低

AC代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 105;
int a[maxn];
int pre[maxn];

int main()
{
    int T, n, m, q;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        pre[0] = 0;
        for(int i = 1; i <= n; i++){
            scanf("%d",&a[i]);
            pre[i] = pre[i-1]^a[i];
        }
        scanf("%d",&m);
        while(m--){
            scanf("%d",&q);
            int len = -1, abs_ = INF;
            for(int i = 1; i <= n; i++){
                for(int j = i; j <= n; j++){
                    int pp = abs((pre[j]^pre[i-1])-q);
                    if( pp < abs_ ){
                        abs_ = pp;
                        len = j-i+1;
                    }
                    else if( pp == abs_ ){
                        len = max(len, j-i+1);
                    }
                }
            }
            printf("%d
", len);
        }
        printf("
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/JinxiSui/p/9740527.html