fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <unordered_map>
  4.  
  5. using namespace std;
  6.  
  7. int n, m;
  8. const int MOD = 1e9 + 7;
  9.  
  10. // Generate all valid states for a column
  11. vector<int> generateValidStates(int n) {
  12. vector<int> states;
  13. int maxState = 1 << n;
  14. for (int state = 0; state < maxState; ++state) {
  15. // Check for vertical adjacency constraint (no two adjacent 1s)
  16. if ((state & (state << 1)) == 0) {
  17. states.push_back(state);
  18. }
  19. }
  20. return states;
  21. }
  22.  
  23. // Precompute transitions between states
  24. unordered_map<int, vector<int>> generateTransitions(const vector<int>& states) {
  25. unordered_map<int, vector<int>> transitions;
  26. for (int s : states) {
  27. for (int s_next : states) {
  28. // Check for horizontal adjacency constraint (no overlapping 1s)
  29. if ((s & s_next) == 0) {
  30. transitions[s].push_back(s_next);
  31. }
  32. }
  33. }
  34. return transitions;
  35. }
  36.  
  37. int main() {
  38. cin >> n >> m;
  39.  
  40. vector<int> states = generateValidStates(n);
  41. unordered_map<int, vector<int>> transitions = generateTransitions(states);
  42.  
  43. // Initialize DP table
  44. unordered_map<int, int> dp_current, dp_next;
  45. for (int state : states) {
  46. dp_current[state] = 1; // Base case: one way to reach each state in the first column
  47. }
  48.  
  49. // DP over columns
  50. for (int col = 1; col < m; ++col) {
  51. dp_next.clear();
  52. for (auto& kv : dp_current) {
  53. int s = kv.first;
  54. int count = kv.second;
  55. for (int s_next : transitions[s]) {
  56. dp_next[s_next] = (dp_next[s_next] + count) % MOD;
  57. }
  58. }
  59. dp_current.swap(dp_next); // Move to the next column
  60. }
  61.  
  62. // Compute final answer
  63. int answer = 0;
  64. for (const auto& kv : dp_current) {
  65. answer = (answer + kv.second) % MOD;
  66. }
  67.  
  68. cout << answer << endl;
  69. return 0;
  70. }
  71.  
Success #stdin #stdout 0.01s 5284KB
stdin
3 4
stdout
227