题目:给定一个数字N,列出1-N序列,每次选中1-N中的某一个数字不断减序列中的任意个数,使得序列中的数字最后都变为0,求该步骤的最少步数。
分析:N = 3, 序列:1 2 3 对1、2减1 变为0 1 3 ;再对1 3 减1 变为 0 0 2 ;再对2减2 变为0 0 0 。得出:总共需要3步。
N = 6, 序列:1 2 3 4 5 6 对4 、5、6 减4 变为0 1 2 ;此时序列相当于N=3时的序列,得出:总共需要1 + 3 = 4步。
N = 7, 序列:1 2 3 4 5 6 7对4 、5、6、 7 减4 变为0 1 2 3;此时序列相当于N=3时的序列,得出:总共需要1 + 3 = 4步。
解析:对所求N先分奇偶,再除2。对于偶数,在dp[N/2]的基础之上再加1。对于奇数,等于其N-1的偶数需要的步数。
注意:本题要求算到1e9,但是一维数组只能算到1e8,但是我发现dp[1e8] = 27,dp[1e9] = 30,所以我利用不断手动二分,算出28、29、30对应的dp下标。
代码如下:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>
#include<cstring>
#include<string>
#include<set>
#include<cmath>
using namespace std;
#define inf 0x3f3f3f3f
const int maxn = 1e8;
typedef long long LL;
int n;
int dp[maxn];
void Table()
{
memset(dp,0,sizeof dp);
dp[1] = 1;
dp[2] = 2;
for(int i = 3; i <= maxn; ++i)
{
if(i % 2 == 1)
{
dp[i] = dp[i-1];
}
else{
dp[i] = 1 + dp[i / 2];
}
}
}
void See()
{
for(int i = 1; i <= 100; ++i)
{
cout << dp[i] << " ";
if(i % 10 == 0){
cout << endl;
}
}
//134217728 28
//536870912 30
//268435456 29
}
int main()
{
Table();
while(scanf("%d",&n) != EOF)
{
if(n <= 100000000)
{
printf("%d\n", dp[n]);
}
if(n > 100000000 && n < 134217728)
{
cout << 27 << endl;
}
else if(n >= 134217728 && n < 268435456)
{
cout << 28 << endl;
}
else if(n >= 268435456 && n < 536870912)
{
cout << 29 << endl;
}
else if(n >= 536870912)
{
cout << 30 << endl;
}
}
}
本文介绍一种算法,用于解决给定数字N时,将1-N序列中所有数字通过选择并减去序列内任意数的方式归零所需的最少步数问题。文中详细解释了针对奇数和偶数N的不同处理方法,并给出了一种有效的动态规划解决方案。
443

被折叠的 条评论
为什么被折叠?



