Problem I
Cubes
Write a program that takes a natural number N and decomposes it as a sum of the minimum number ofexact natural cubes. The program should find m1, m2, ..., mk, such that each mi is a natural number,m13 +m23 +...+mk3 =N, and k is minimal.
Input
The only line of the input file contains the number N (1 ≤ N ≤ 44,777,444).Output
Your program should write exactly two lines. The first line contains the number k - the minimumnumber of natural cubes. The second line contains k space-separated natural numbers - thatraised to the power of 3 sum to N.
Sample input |
Sample output |
42 |
7 |
43 |
3 |
题意:
输入一个数n,将这个数写成k个数的立方和的形式,求出最小的k,并输出这k个数。
题解:
分析之后可以明显感觉解得深度不会很深,然后应该下降的很快,所以设置一个上限dfs,其中加上最优化剪枝,比较小的数的部分我们可以预处理出来加快速度。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define fi first
#define se second
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
const int inf=0x3fffffff;
const ll mod=1000000007;
const int maxn=1e5+10;
const int E=1e5;
int pre[maxn],f[maxn];
int n;
int ans,res;
int tmp[maxn],a[maxn];
int num=0;
void init() //预处理小数
{
f[0]=0;pre[0]=0;
for(int i=1;i<=E;i++)
f[i]=inf;
for(int i=1;i<=E;i++)
{
for(int j=1;j*j*j<=i;j++)
{
if(f[i-j*j*j]+1<f[i])
{
f[i]=f[i-j*j*j]+1;
pre[i]=j;
}
}
}
}
void dfs(int x,int d,int k)
{
if(x<=E)
{
if(f[x]+d<ans)
{
ans=f[x]+d;
num=d;
for(int i=1;i<=d;i++)
a[i]=tmp[i];
res=x;
}
return;
}
if((d+max(1,x/(k*k*k)))>=ans) //剪枝
return;
for(int i=k;i>0;i--)
if(i*i*i<=x)
{
tmp[d+1]=i;
dfs(x-i*i*i,d+1,i);
}
}
void output(int x) //对于小于等于E的数输出结果
{
while(x)
{
printf("%d ",pre[x]);
x-=pre[x]*pre[x]*pre[x];
}
}
int main()
{
init();
scanf("%d",&n);
if(n<=E)
{
ans=f[n];
printf("%d\n",ans);
output(n);
puts("");
}
else
{
ans=inf;
num=0;
dfs(n,0,1000);
printf("%d\n",ans);
for(int i=1;i<=num;i++)
printf("%d ",a[i]);
if(res) output(res);
puts("");
}
return 0;
}