时间限制:1000MS 代码长度限制:10KB
提交次数:217 通过次数:58
题型: 编程题 语言: G++;GCC
Description
有N个士兵站成一队列, 现在需要选择几个士兵派去侦察。
为了选择合适的士兵, 多次进行如下操作: 如果队列超过三个士兵, 那么去除掉所有站立位置为奇数的士兵,
或者是去除掉所有站立位置为偶数的士兵。直到不超过三个战士,他们将被送去侦察。现要求统计按这样的方法,
总共可能有多少种不同的正好三个士兵去侦察的士兵组合方案。
注: 按上法得到少于三士兵的情况不统计。
1 <= N <= 2的32次方-1
输入格式
有多行(可能有上百行,尽量优化代码),每行一个数字N,最后一行是0
输出格式
对每一行的数字N,输出针对N的方案数
直到没有数字
输入样例
10
4
0
输出样例
2
0
作者 admin
解题思路:关键是将代码进行优化。
未经优化:
#include<iostream>
using namespace std;
int f(int n)
{
if(n<=3)
return n==3?1:0;
return f(n/2)+f((n+1)/2);
}
int main()
{
int n;
while(cin>>n&&n)
{
cout<<f(n)<<endl;
}
return 0;
}
优化偶数:
#include<iostream>
using namespace std;
int f(int n)
{
if(n<=3)
return n==3?1:0;
if(n%2==0)
return 2*f(n/2);
return f(n/2)+f(n/2+1);
}
int main()
{
int n;
while(cin>>n&&n)
{
cout<<f(n)<<endl;
}
return 0;
}
整体利用状态数组进行优化(注意:状态数组不可开得过大):
#include<iostream>
using namespace std;
int v[1000002];
int f(int n)
{
if(n==3)
return v[n]=1;
if(n<3)
return v[n]=0;
if(n<=1000000&&v[n]==0)
{
return v[n]=f(n/2)+f((n+1)/2);
}
else if(n<=1000000&&v[n]!=0)
return v[n];
else if(n>1000000)
return f(n/2)+f((n+1)/2);
}
int main()
{
int n;
while(cin>>n&&n)
{
cout<<f(n)<<endl;
}
return 0;
}