小白进阶之路-Xorto-暴力枚举优化

题目链接:https://ac.nowcoder.com/acm/problem/14247

思想:暴力枚举两个区间的左右端点时间复杂度很高,可如果枚举一个区间,问题会简化。

         维护到 i 处的异或和(pre[i],类似于桶排序中的桶,所以num数组开大点),枚举右区间加上左区间与当前区间异或值相等的数量,就是答案。

Thinking!Finghting!

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;


int pre[10002],num[3200000];
// pre[i] 表示从 1 ~ i 的前缀异或和, num[i] 表示当前异或值为 i 的数量
int main() { int n; while(~scanf("%d",&n)){ memset(num,0,sizeof(num)); pre[0] = 0; for(int i = 1 ;i <= n;i++){ int x;scanf("%d",&x);pre[i] = pre[i-1] ^ x; } long long ans = 0; for(int i = 1; i <= n;i++){ // 枚举 1 ~ n for(int j = i;j >= 1;j--){ // 更新 1 ~ i 之间的异或和数量 num[pre[i] ^ pre[j-1]]++; // pre[i] - pre[j-1] 表示 i ~ j 这段的异或和 } for(int j = i;j < n;j++){ // 以 [i,j] 为右区间,那么左区间中与当前区间异或值相等的数量相加就是答案 ans += num[pre[i] ^ pre[j+1]]; } } printf("%lld\n",ans); } return 0; }

猜你喜欢

转载自www.cnblogs.com/Wise-XiaoWei4/p/12757765.html