Hanoi Tower Troubles Again!

http://acm.zju.edu.cn/show_problem.php?pid=1239

Time limit: 1 Seconds

Memory limit: 32768K

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.

1239.jpg

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.

1. 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.

2. 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.

3. Sample Input

2
4
25

4. Sample Output

11
337

Problem Source: OIBH Reminiscence Programming Contest


   1 //2007-01-21 17:58:29 Accepted 1239 C++ 00:00.00 396K 
   2 //模拟并记录前50项
   3 #include <stdio.h>
   4 #include <math.h>
   5 
   6 int res[52];
   7 int top[52];
   8 
   9 int main(){
  10         int cur = 1;                    //当前数
  11         int n = 1;                      //已经知道的最大结果+1
  12         int i;
  13         bool bb;                        //是否在前n-1列找到合适位置
  14         double tem;
  15         while( n<52 ){
  16                 bb = false;
  17                 for(i=1; i<n; i++){                     
  18                         if( (tem=sqrt(1.0*top[i]+cur))==(int)tem ){
  19                                 bb = true;
  20                                 top[i] = cur;
  21                                 break;
  22                         }
  23                 }
  24                 if( !bb ){
  25                         //没有合适的地方,新增第n列,
  26                         //并记录前n-1列最多能放的球数目
  27                         top[n] = cur;
  28                         res[n-1] = cur-1;
  29                         n ++;
  30                 }
  31                 cur ++;
  32         }
  33         //input and output
  34         scanf("%d", &n);
  35         while( n-- ){
  36                 scanf("%d", &i);
  37                 printf("%d\n", res[i]);
  38         }
  39         return 1;
  40 }

zju1239 (2008-02-23 15:34:59由localhost编辑)

ch3n2k.com | Copyright (c) 2004-2020 czk.