People stopped moving discs from peg to peg after they know the number of steps needed to complete the entire task. But on the other hand, they didn't not stopped thinking about similar puzzles with the Hanoi Tower. Mr.S invented a little
game on it. The game consists of N pegs and a LOT of balls. The balls are numbered 1,2,3... The balls look ordinary, but they are actually magic. If the sum of the numbers on two balls is NOT a square number, they will push each other with a great force when
they're too closed, so they can NEVER be put together touching each other.
The player should place one ball on the top of a peg at a time. He should first try ball 1, then ball 2, then ball 3... If he fails to do so, the game ends. Help the player to place as many balls as possible. You may take a look at the picture above, since it shows us a best result for 4 pegs.
Input
The first line of the input contains a single integer T, indicating the number of test cases. (1<=T<=50) Each test case contains a single integer N(1<=N<=50), indicating the number of pegs available.
Output
For each test case in the input print a line containing an integer indicating the maximal number of balls that can be placed. Print -1 if an infinite number of balls can be placed.
Sample Input
2
4
25
Sample Output
11
337
问题链接:UVa10276 HDU1329 ZOJ1239 Hanoi Tower Troubles Again!。
题意简述:
人们在知道完成整个任务所需的步骤数之后, 停止将光盘从 peg 移动到 peg。但另一方面, 他们并没有停止思考与河内塔类似的谜题。Mr. s 发明了一个小游戏。游戏由 n 个柱子和许多球组成。球是编号 1,2,3...。球看起来很普通, 但实际上是魔术。如果两个球上的数字的总和不是一个平方数, 当它们太封闭时, 它们会以很大的力量互相推挤, 所以它们永远不能被放在一起互相接触。
玩家应该一次把一个球放在柱子上。他应该先试球 1, 然后球 2, 然后球 3...。如果他不这样做, 游戏结束。帮助球员尽可能多地放置球。你可以看看上面的图片, 因为它显示了我们4柱子的最佳结果。
问题分析:
这个问题,用模拟法应该是可以做出来的,因为柱子数最多不过50而已。
另外一种方法是构建一个递推函数来计算。
h(1)=1:1个柱子时,放上1之后,2就放不上去了,不满足柱子上相邻的球之和为平方数(1+2=3,不是平方数);
h(2)=3:2个柱子时,1和2各放在1个柱子上,3可以放在1上面(1+3=4=2^2);
h(i)=h(i-1)+i+1:i为奇数时,在i-1柱子的基础上增加了一个柱子,这时候可以再放i+1个球(需要数学证明);
h(i)=h(i-1)+i:i为偶数时,在i-1柱子的基础上增加了一个柱子,这时候可以再放i个球(需要数学证明)。
AC的C++语言程序如下:
/* UVa10276 HDU1329 ZOJ1239 Hanoi Tower Troubles Again! */ #include <iostream> using namespace std; const int N = 50; int hanoi[N+1]; void sethanoi(int n) { hanoi[1] = 1; hanoi[2] = 3; for(int i=3; i<=n; i++) if(i % 2) hanoi[i] = hanoi[i - 1] + i + 1; // 奇数 else hanoi[i] = hanoi[i - 1] + i; // 偶数 } int main() { int t, n; sethanoi(N); cin >> t; while(t--) { cin >> n; cout << hanoi[n] << endl; } return 0; }