fork download
  1. #include <iostream>
  2. #include <utility>
  3. #include <algorithm>
  4. #include <vector>
  5. using namespace std;
  6.  
  7. struct Piece {
  8. int idx;
  9. int left;
  10. int right;
  11. };
  12.  
  13. bool operator<( const Piece & a, const Piece & b ) {
  14. if ( a.left < b.left ) return true;
  15. if ( a.left > b.left ) return false;
  16. if ( a.right < b.right ) return true;
  17. if ( a.right > b.right ) return false;
  18. return false;
  19. }
  20.  
  21. const Piece findPiece( const std::vector< Piece > & v, const Piece & p ) {
  22. return *std::find_if( v.begin(), v.end(), [ p ]( const Piece & i ) {
  23. return p.idx == i.idx;
  24. } );
  25. }
  26.  
  27. int main() {
  28. std::vector< Piece > dominos = {
  29. { 1, 1, 2 },
  30. { 2, 2, 4 },
  31. { 3, 2, 4 },
  32. { 4, 6, 4 },
  33. { 5, 2, 1 }
  34. };
  35. std::vector< Piece > dominosCopy{ dominos };
  36. bool all = false;
  37. std::vector< std::vector< Piece > > allPerm;
  38. do {
  39. allPerm.emplace_back( dominos.begin(), dominos.end() );
  40. } while ( std::next_permutation( dominos.begin(), dominos.end() ) );
  41. const int count = dominos.size();
  42. int goodPerm;
  43. for ( int perm = 0, size = allPerm.size(); perm < size && ! all; perm++ ) {
  44. bool ok = true;
  45. std::vector< Piece > & d = allPerm[ perm ];
  46. for ( int i = 1; i < count && ok; i++ ) {
  47. //cout << "( " << d[ i - 1 ].idx << " ) [ " << d[ i - 1 ].left << " " << d[ i - 1 ].right << " ] ";
  48. if ( d[ i ].left == d[ i - 1 ].right || d[ i ].right == d[ i - 1 ].right ) {
  49. if ( d[ i ].right == d[ i - 1 ].right ) {
  50. std::swap( d[ i ].left, d[ i ].right );
  51. }
  52. }
  53. else {
  54. ok = false;
  55. }
  56. }
  57. //cout << "( " << d[ count - 1 ].idx << " ) [ " << d[ count - 1 ].left << " " << d[ count - 1 ].right << " ]" << endl;
  58. if ( ok ) {
  59. goodPerm = perm;
  60. all = true;
  61. }
  62. }
  63. if ( all ) {
  64. for ( const Piece & p : allPerm[ goodPerm ] ) {
  65. const Piece pCopy = findPiece( dominosCopy, p );
  66. cout << p.idx << " " << ( ( pCopy.left == p.left ) ? "+" : "-" );
  67. cout << " [ " << pCopy.left << " " << pCopy.right << " ]" << endl;
  68. }
  69. }
  70. else {
  71. cout << "No solution" << endl;
  72. }
  73. return 0;
  74. }
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
4 +  [ 6 4 ]
3 -  [ 2 4 ]
1 -  [ 1 2 ]
5 -  [ 2 1 ]
2 +  [ 2 4 ]