2012年9月20日 星期四

uva 10276 - Hanoi Tower Troubles Again!

Problem H
Hanoi Tower Troubles Again!
Input: Standard Input
Output: Standard Output
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
__________________________________________________________________________________________
Rujia Liu


DFS, O(1) solution exists here 

#include<stdio.h>
#include<cstring>
#include<cmath>
#include<string>
#include<vector>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define DBG 0
using namespace std;

//bool trav[10000];
int LM,N;
int top[50];
bool isSqr(int c){
int a=int(sqrt(c));
return a*a==c;
}
void DFS(int cur,int len){
if(cur-1>LM)LM=cur-1;
int b;
rep(i,min(len+1,N)){
if(cur>LM-N&&(isSqr(top[i]+cur)||top[i]==0)){
if(DBG)printf("LM-N top cur loc %d %d %d %d\n",LM-N, top[i],cur,i);
b=top[i],top[i]=cur;
DFS(cur+1,min(max(i+2,len),N));
top[i]=b;
}
}
}
void ans(){
LM=0;
DFS(1,1);
printf("%d\n",LM);
}
int main(){
int n;
scanf("%d",&n);
rep(i,n)scanf("%d",&N),ans();
}

沒有留言:

張貼留言