Hanoi IV (recursion + math)

Source: Internet
Author: User
Tags pow
Hanoi IV Time limit:1000/1000 MS (java/others) Memory limit:32768/32768 K (java/others)
Total submission (s): 4989 Accepted Submission (s): 3631


Problem Description remember Hanoi III. His rule is this: it is not allowed to move directly from the leftmost (right) edge to the right (left) side (each move must be moved to the middle or from the center), nor is it allowed to be placed on top of the small plate. XHD wondered what would happen if we allowed the largest plate to be put on top. (Only the maximum is allowed on top) of course the final result is that the tray is from small to large to the right.

The first line of input data is a data T, which indicates that there is a T group of data.
Each group of data has a positive integer n (1 <= n <= 20), which indicates that there are n plates.

Output for each set of input data, the minimum number of places required.

Sample Input
2 1 10
Sample Output
2 19684
/* Because the largest can be placed on the top, so you can not like Hanoi III as the former n-1 all from 1->3.  
As long as the front n-1 a disk from the 1->2, and then the nth disk 1->2->3, and then the front n-1 a disk 2->3, so it is done.
So, the question is now how many times to move one step into n disk.   We can see that, in addition to the last
largest disk n, the first n-1 disk is moved in the same way as the Hanoi III rule. So we first 1->3 the first
n-2, then the n-1 disk 1->2, then the front n-2 a disk 3->2 , so that the front n-1 disk
1->2 moved a step.
Because the method of Hanoi III to find the n disk 1->3 needs 3^n-1  :
So according to the rules of Hanoi IV, moving n disks requires: F (n) = 3^ (n-1) + 1*/
#include <STDIO.H&G t;
#include <string.h>
__int64 pow (int x,int y)
{
	__int64 val=1;
	for (int i=1;i<=y;i++)
	{
		val*=x;
	}
	return val;
}
int main () {
	int t,n;
	scanf ("%d", &t);
	while (t--)
	{
		scanf ("%d", &n);
		printf ("%i64d\n", pow (3,n-1) +1);
	}
	return 0;
} 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.