Even Subarrays(数论问题)
题目描述:
You are given an integer array
Find the number of subarrays of a whose XOR has an even number of divisors. In other words, find all pairs of indices
For example, numbers
Here XOR (or
Print the number of subarrays but multiplied by 2022... Okay, let's stop. Just print the actual answer.
输入描述:
Each test contains multiple test cases. The first line contains the number of test cases
The first line of each test case contains a single integer
The second line contains n integers
It is guaranteed that the sum of
输入描述:
For each test case, print the number of subarrays, whose XOR has an even number of divisors.
样例:
input:
4
3
3 1 2
5
4 2 1 5 3
4
4 4 4 4
7
5 7 3 7 1 7 3
output:
4
11
0
20
Note:
In the first test case, there are
In the second test case, there are
In the third test case, there is no subarray whose XOR has an even number of divisors since XOR of any subarray is either
AC代码:
#include <bits/stdc++.h> using namespace std; typedef long long LL; const int N = 2e5 + 10; int T = 1; LL n; void solve() { scanf("%lld", &n); vector<int> a(n), b(2 * n); // 开两个vector,一个用于存数组,一个用于存某个数出现的次数 a.clear(), b.clear(); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } LL cnt = 0; // 存储异或和的因数为奇数个的数的个数 int t = 0; b[t]++; // a[0] ^ a[0]为0 for (int i = 0; i < n; i++) { t ^= a[i]; // n个数可能的异或最大值肯定小于2 * n // 判断某个数的因数是否为奇数的条件就是判断其是否是完全平方数 for (LL j = 0; j * j < 2 * n; j++) { // 一个数 t 异或一个完全平方数 p 的结果 x,该结果 x 异或 t 的结果必定是那个完全平方数 p,只要 x 存在,则 j * j 必存在 // t 是 1-i 的异或和,假设 p 是 j-i 的异或和,则 x 就是 1-(j-1) 的异或和,所以 x ^ p = t,所以此时只需要判断 x 出现过的次数即可 if ((t ^ (j * j)) < 2 * n) { cnt += b[t ^ (j * j)]; // cnt 加上这个数出现过的次数 } } b[t]++; // t的出现的次数加一 } LL ans = (n * (n + 1) / 2) - cnt; // 总共的个数减去不成立的个数即为成立的个数 printf("%lld\n", ans); } int main() { // ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); scanf("%d", &T); while (T--) { solve(); } return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】