problem364.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/env python
  2. from copy import copy
  3. from sys import argv, exit, setrecursionlimit
  4. setrecursionlimit(10000000)
  5. def T(N, seats=None):
  6. if not seats:
  7. seats = [False] * N
  8. elif all(seats):
  9. return 1
  10. t = 0
  11. seated = False
  12. # 1. If there is any seat whose adjacent seat(s) are not occupied, take
  13. # such a seat
  14. for i, taken in enumerate(seats):
  15. if not taken and (not i or not seats[i - 1]) \
  16. and (i == N - 1 or not seats[i + 1]):
  17. new_seats = copy(seats)
  18. new_seats[i] = True
  19. t += T(N, new_seats)
  20. seated = True
  21. # 2. If there is no such seat and there is any seat for which only one
  22. # adjacent seat is occupied take such a seat
  23. if not seated:
  24. for i, taken in enumerate(seats):
  25. if not taken and ((not i and seats[1]) \
  26. or (i == N - 1 and seats[N - 2])
  27. or (seats[i - 1] ^ seats[i + 1])):
  28. new_seats = copy(seats)
  29. new_seats[i] = True
  30. t += T(N, new_seats)
  31. seated = True
  32. # 3.Otherwise take one of the remaining available seats
  33. if not seated:
  34. for i, taken in enumerate(seats):
  35. if not taken:
  36. new_seats = copy(seats)
  37. new_seats[i] = True
  38. t += T(N, new_seats)
  39. del seats
  40. return t
  41. if len(argv) < 2:
  42. print 'Usage: python %s N' % argv[0]
  43. exit(1)
  44. print T(int(argv[1])) % 100000007