Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2020
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1.  
  2. Bitmasking
  3.  
  4. What is bitmasking?
  5. #1 it is a method of brute force (it tries all possible combinations)
  6. #2 only use when constraints of the number are less than 20
  7. #3 it has complexity O(2^n*n);
  8.  
  9. Can u write the first 8 numbers in binary
  10.  
  11.  
  12. 0 000 // {empty}
  13. 1 001 // {c}
  14. 2 010 // {b}
  15. 3 011 // {b,c}
  16. 4 100 // {a}
  17. 5 101 // {a,c}
  18. 6 110 // {a,b}
  19. 7 111 // {a,b,c}
  20.  
  21. All possible subsets of size 0 = 1 = {empty}
  22. All possible subsets of size 1 = 3 = {a,b,c}
  23. All possible subsets of size 2 = 3 = {no a , no b , no c}
  24. All possible subsets of size 3 = 1 = {a,b,c}
  25.  
  26. arr = ['a','b','c']
  27.  
  28. 1. left shift operator
  29. 1<<2 = 4
  30.  
  31. 2. bitwise
  32. 1 & 1 = 1 ; everything else = 0;
  33.  
  34.  
  35. Bitmasking code
  36.  
  37. for(int i = 0 ; i < 1<<n ; i++)
  38. {
  39. for(int j = 0 ; j < n ; j++)
  40. {
  41. if((i)&&(1<<j)) // what is this line doing ? (it checks if the jth bit is set in the number 'i')
  42. {
  43. cout<<a[j]<<" ";
  44. }
  45. }
  46. cout<<endl;
  47. }
  48.  
  49. Qn) When do you use it ?
  50.  
  51. a = [10, 20 ,30]
  52. int flag = 1;
  53.  
  54.  
  55.  
  56.  
  57.  
  58. #include <bits/stdc++.h>
  59. using namespace std;
  60.  
  61. int main()
  62. {
  63. int n;
  64. cin >> n;
  65. int a[n]; // wrong because if u declare array of variable size u cant initialize
  66. int flag = 1;
  67. for(int i= 0 ; i< n ; i++)
  68. {
  69. cin>>a[i];
  70. }
  71. for(int i = 0 ; i < 1<<n ; i++)
  72. {
  73. int sums = 0 ;
  74. for(int j = 0 ; j < n ; j++)
  75. {
  76. if((i)&(1<<j)) // what is this line doing ? (it checks if the jth bit is set in the number 'i')
  77. {
  78. sums += a[j];
  79. } else{
  80. sums -= a[j];
  81. }
  82. }
  83.  
  84. if (sums%360 == 0){
  85. flag = 0 ;
  86. cout<<"Yes"<<endl;
  87. break;
  88. }
  89.  
  90. }
  91. if (flag == 1){
  92. cout<<"No"<<endl;
  93. }
  94. }
  95.  
  96.  
  97. 120 + 120 + 120 = 360 = 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement