欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HDU1329 Hanoi Tower Troubles Again!

程序员文章站 2022-04-06 13:50:21
...
问题描述:
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.

HDU1329 Hanoi Tower Troubles Again!


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

思路:直接dfs就可以了

#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;

int peg[55];
int n,ans;
void dfs(int p,int s){
	if(p > n){
		ans = s-1;
		return;
	}	
	ans = floor((double)sqrt(s + peg[p]));
	if(peg[p] == 0 || ans * ans == s+peg[p] ){
		peg[p] = s;
		dfs(1,++s);
	}
	else
		dfs(++p,s);
	
}

int main(){
	int t,m;
	cin >> t;
	while(t--){
		cin >> n;
		ans = 0;
		memset(peg,0,sizeof(peg));
		dfs(1, 1);
		cout << ans << endl;
	}
	return 0;
} 

相关标签: HDU