10254-the Priest mathematician
Time limit:3.000 seconds
Http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=34&page=show_problem &problem=1195
The ancient folklore behind the "Towers of Hanoi" puzzle invented by E. Lucas in 1883 is quite-ok known to us. One more recent legend tells us this Brahmin monks from Benares never the "the world believed could" at the vanish NT they finished to transfer the "discs from" needle on which they were to one of the other needles, and they decided To finish the task as soon as possible.
Fig:the Four Needle (Peg) Tower of Hanoi
One of the priests at the Benares temple (who loved the mathematics) assured their colleagues to achieve the transfer in T He afternoon (the rhythm they had thought is a disc-per-second) by using a additional needle. They couldn ' t believe him, but he proposed them the following strategy:
--The topmost discs (say the top K discs) to one of the spare needles.
--Then use the "standard three needles strategy to move the remaining N-k" (for A and n discs) to discs Destination.
-Finally, move the top K discs into their final destination using the four needles.
He calculated the ' value to K ' in order to minimize the number of movements and get a total of 18433 transfers, so they spen T just 5 hours, 7minutes seconds against the more than 500000 millions years without the additional needle (as they Would have to do 2^64-1 disc transfers. Can you believe it?)
Try to follow the clever priest's strategy and calculate the number of transfer using four needles but according with the Fixed and immutable laws of Brahma, which require that "priest on duty" not "move" more must one than in a time and T Hat He must the place this disc to a needle so, there is no smaller disc it. Of course, the main goal is to calculate the K-minimize the number of transfers (even thought it is isn't know for sure That is always the optimal number of movements).
Input
The input file contains several lines of input. Each line contains a single integer N and which is the number of disks to be transferred. here0<=n<=10000. The Input is terminated by the end of file.
Output
For each line of input produce one line of output which indicates the number of movements required to transfer the N disks To the final needle.
Sample Input:
1
2
28
64
Sample Output:
1
3
769
18433
Ideas:
The strategies given by the topic are:
F (1) =1, f (n) =min{2*f (k) +2^ (N-k)-1} (1<=k<=n-1)
Print previous items: 1,3,5,9,13,17,25,33,41,49,65,...
To compute the first order difference sequence Δf (n): 2,2,4,4,4,8,8,8,8,16,...
Found 2^m appeared (m+1) times, m>=0
The preprocessing of all solutions is based on this.
More discussion: "Concrete Mathematics" P16 17th question, 25th question