BitSet.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // ensemble d'entiers entre 0 et MAXN-1
  2. typedef long long T;
  3. const int MAXN = 5000;
  4. const int BITS = (sizeof(T)*8);
  5. const int SIZE = ((MAXN+BITS-1)/BITS); // size of arrays
  6. void clear(T a[]) {
  7. memset(a, 0, sizeof(T[SIZE]));
  8. }
  9. void diff(T a[], T b[], T rep[]) {
  10. for(int i = 0; i < SIZE; i++)
  11. rep[i] = (a[i] ^ b[i]) & a[i];
  12. }
  13. void inter(T a[], T b[], T rep[]) {
  14. for(int i = 0; i < SIZE; i++)
  15. rep[i] = a[i] & b[i];
  16. }
  17. // union : idem with |
  18. // symmetric difference : idem with ^
  19. int size(T a[]) {
  20. int r = 0;
  21. for(int i = 0; i < SIZE; i++)
  22. r += __builtin_popcountll(a[i]); // pour long long
  23. return r;
  24. }
  25. void insert(T a[], int x) {
  26. a[x/BITS] |= ((T)1) << (x%BITS);
  27. }
  28. void del(T a[], int x) {
  29. a[x/BITS] &= ~(((T)1) << (x%BITS));
  30. }
  31. void print(T a[]) {
  32. for(int i = 0; i < SIZE; i++)
  33. for(int j = 0; j < BITS; j++)
  34. if(a[i] & (((T)1)<<j))
  35. printf("%d ", i*BITS+j);
  36. printf("\n");
  37. }
  38. int getFirst(T a) { // return the smallest element in a, or -1 if a is empty
  39. return __builtin_ffsll(a)-1; // pour long long
  40. }
  41. bool test(T a[], int x) {
  42. return a[x/BITS] & (((T)1) << (x%BITS));
  43. }