Advertisement
Guest User

rectangles

a guest
Jul 25th, 2010
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. #include <vector>
  2. #include <algorithm>
  3. #include <iostream>
  4.  
  5. using namespace std;
  6. const int N = 5;
  7.  
  8. int mask2bits[1 << N];
  9. int mask2bitsAllSet = 0; // 1023 = 1111111111 binary
  10.  
  11. // count the number of bits set in x
  12. int popcnt( int x )
  13. {
  14. return x ? popcnt(x&(x-1))+1 : 0;
  15. }
  16.  
  17. //
  18. void initMask2bits()
  19. {
  20. int ct = 0;
  21. for ( int i = 0; i < (1<<N); i++ )
  22. {
  23. int pop = popcnt( i );
  24. mask2bits[i] = pop == 2 ? 1 << ct++ : 0;
  25. }
  26. mask2bitsAllSet = (1<<ct)-1;
  27. }
  28.  
  29. bool check( int a[], int b[] )
  30. {
  31. int m = 0;
  32. int masky = 0;
  33. // scan top-to-bottom left-to-right
  34. for ( int y = 0; y < N*2; y++ )
  35. {
  36. masky ^= 1 << b[y]; // masky keeps track of which rectangles are currently on, considering only y-coordinate
  37. // 00001 (binary) means just rectangle 0
  38. // 00010 (binary) means just rectangle 1
  39. // 00011 (binary) means just rectangle 0 and 1
  40. int maskx = 0;
  41. for ( int x = 0; x < N*2; x++ )
  42. {
  43. maskx ^= 1 << a[x]; // masky keeps track of which rectangles are currently on, considering only y-coordinate
  44. m |= mask2bits[maskx&masky]; // maskx&masky determines which rectangles are active at x,y
  45. // if that value has exactly 2 bits set, we keep track of that in 'm'
  46. // 'm' is another bitmask with 10 positions that must be set for a winner
  47. }
  48. }
  49. return m == mask2bitsAllSet;
  50. }
  51. int main(int n,char**p)
  52. {
  53. initMask2bits();
  54. int a[] = {0,1,2,3,4,0,1,2,3,4}; // relative order of rectangle start or stop on x-axis
  55. int b[] = {0,1,2,3,4,0,1,2,3,4}; // relative order of rectangle start or stop on y-axis
  56. int x = 0;
  57. do {
  58. do {
  59. do { // for every permutation of first/last 5 elements of y and last 5 elements of x
  60. if ( check( a, b ) ) // check if we have a winner
  61. {
  62. for ( int i = 0; i < N*2; i++ ) cout << a[i] << " "; cout << endl;
  63. for ( int i = 0; i < N*2; i++ ) cout << b[i] << " "; cout << endl;
  64. return 0;
  65. }
  66. } while( next_permutation( b+N, b+N*2 ) );
  67. } while( next_permutation( b+0, b+N ) );
  68. } while( next_permutation( a+N, a+N*2 ) );
  69. cout << "found no match" << endl;
  70. return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement