I am trying to solve this problem in Python. Noting that only the first kiss requires the alternation, any kiss that is not a part of the chain due to the first kiss can very well have a hug on the 2nd next person, this is the code I have come up with. This is just a simple mathematical calculation, no looping, no iteration, nothing. But still I am getting a timed-out message. Any means to optimize it?
import psyco
psyco.full()
testcase = int(raw_input())
for i in xrange(0,testcase):
n = int(raw_input())
if n%2:
m = n/2;
ans = 2 + 4*(2**m-1);
ans = ans%1000000007;
print ans
else:
m = n/2 - 1
ans = 2 + 2**(n/2) + 4*(2**m-1);
ans = ans%1000000007
print ans
The answer to this is a pretty simple recursion.
F(1) = 2and forF(n)we have two choices:n = H, then the number of ways to kiss the remaining guests is simplyF(n-1)n = K, then the number of ways to kiss the remaining guests is2 ** kwherekis the number of remaining guests that the princess is not forced to kiss. Since she has to kiss every second remaining guest,k = ceil((n - 1) / 2)Putting them together, we get
F(n) = F(n - 1) + 2 ** ceil((n - 1) / 2)My attempt, including taking everything mod 1000000007:
EDIT: Updated (much faster and more unreadable!
F(1e9)takes about 3 minutes):EDIT 2: After further thought, I realised the above is actually just:
But if
nis even, the last2 ** n/2only occurs once, so we have:Which runs much faster! (Limited by the speed of
pow(x, y, z), which I think isO(lg n)?)And just because, here is the one-liner:
Results: