Beingamanforever

XOR Sum 2

Jan 22nd, 2025
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. // #include <atcoder/all>
  3. using namespace std;
  4. #define int long long
  5. #define all(x) (x).begin(), (x).end()
  6. typedef vector<int> vi;
  7. typedef vector<vi> vvi;
  8. typedef vector<pair<int, int>> vpi;
  9. typedef pair<int, int> pi;
  10. #define f first
  11. #define s second
  12. #define pb push_back
  13. #define endl "\n"
  14. #define yes cout << "YES" << endl
  15. #define no cout << "NO" << endl
  16. #define init(x, a) memset(x, a, sizeof(x))
  17. const int mod1 = 1e9 + 7, mod2 = 998244353, INF = 2e18, N = 2e5 + 5, L = 19;
  18. int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
  19. // -----------------------------------------------------------------------------
  20.  
  21. void solve()
  22. {
  23.     int n;
  24.     cin >> n;
  25.     vi a(n); // a[i] < 2^20
  26.     vi prefxor(n + 1, 0), prefsum(n + 1, 0);
  27.     for (int i = 0; i < n; i++)
  28.     {
  29.         cin >> a[i];
  30.         prefxor[i + 1] = prefxor[i] ^ a[i];
  31.         prefsum[i + 1] = prefsum[i] + a[i];
  32.     }
  33.     // acc to pigeonhole principle, we can have subarray size of atmost 20
  34.     // if it's more than 20, then 1 bit would he repeated, so carry over would be there so XOR != SUM
  35.     int ans = 0;
  36.     for (int k = 0; k < 25; k++) // subarray length
  37.     {
  38.         for (int i = 0; i < n; i++)
  39.         {
  40.             if (i + k >= n)
  41.             {
  42.                 break;
  43.             }
  44.             int x = prefxor[i] ^ prefxor[i + k + 1];
  45.             int y = prefsum[i + k + 1] - prefsum[i];
  46.             if (x == y)
  47.             {
  48.                 ans++;
  49.             }
  50.         }
  51.     }
  52.     cout << ans << endl;
  53.     return;
  54. }
  55.  
  56. signed main()
  57. {
  58.     // __START__;
  59.     ios_base::sync_with_stdio(false);
  60.     cin.tie(NULL);
  61.     cout.tie(NULL);
  62.     int t = 1;
  63.     // cin >> t;
  64.     while (t--)
  65.     {
  66.         solve();
  67.     }
  68.     // __END__;
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment