Advertisement
Guest User

Untitled

a guest
Jan 20th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #include "jngen.h"
  3. using namespace std;
  4. #define forn(i, n) for (int i = 0; i < n; ++i)
  5.  
  6. const int N = 100000;
  7. bitset<N> a;
  8.  
  9. int count0(int l, int r) {
  10.     int s = 0;
  11.     for (int i = l; i < r; ++i) {
  12.         s += a.test(i);
  13.     }
  14.     return s;
  15. }
  16.  
  17. int count1(int l, int r) {
  18.     return (a >> l).count() - (a >> r).count();
  19. }
  20.  
  21. int count2(int l, int r) {
  22.     int s = 0;
  23.     const unsigned char* c = reinterpret_cast<const unsigned char*>(&a);
  24.     if (l/8 == r/8) {
  25.         return __builtin_popcount((c[l/8] & ((1 << (r%8)) - 1)) >> l%8);
  26.     }
  27.     s += __builtin_popcount(c[l/8] >> (l % 8));
  28.     for (int i = l/8 + 1; i < r/8; ++i) {
  29.         s += __builtin_popcount(c[i]);
  30.     }
  31.     s += __builtin_popcount((c[r/8] << (8 - r % 8)) & 0xff);
  32.     return s;
  33. }
  34.  
  35. int count3(int l, int r) {
  36.     int s = 0;
  37.     const unsigned int* c = reinterpret_cast<const unsigned int*>(&a);
  38.     if (l/32 == r/32) {
  39.         return __builtin_popcount((c[l/32] & ((1 << (r%32)) - 1)) >> l%32);
  40.     }
  41.     s += __builtin_popcount(c[l/32] >> (l % 32));
  42.     for (int i = l/32 + 1; i < r/32; ++i) {
  43.         s += __builtin_popcount(c[i]);
  44.     }
  45.     if (r%32 != 0) {
  46.         s += __builtin_popcount((c[r/32] << (32 - r % 32)));
  47.     }
  48.     return s;
  49. }
  50.  
  51. int main() {
  52.     registerGen(0, nullptr);
  53.     forn(i, N) a[i] = rnd.next(2);
  54.  
  55.     auto q = Arrayp::random(100000, 0, N, odpair);
  56.  
  57.     long long s1 = 0;
  58.     {
  59.         ContextTimer timer("naive");
  60.         for (auto lr: q) s1 += count0(lr.first, lr.second);
  61.     }
  62.  
  63.     long long s2 = 0;
  64.     {
  65.         ContextTimer timer("count");
  66.         for (auto lr: q) s2 += count1(lr.first, lr.second);
  67.     }
  68.  
  69.     long long s3 = 0;
  70.     {
  71.         ContextTimer timer("manual");
  72.         for (auto lr: q) s3 += count2(lr.first, lr.second);
  73.     }
  74.  
  75.     long long s4 = 0;
  76.     {
  77.         ContextTimer timer("manual_int");
  78.         for (auto lr: q) s4 += count3(lr.first, lr.second);
  79.     }
  80.  
  81.     assert(s1 == s2);
  82.     assert(s2 == s3);
  83.     assert(s2 == s4);
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement