gym101164I(搜索+剪枝)

题目链接

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.

page10image12624

Sample input

page10image14016

Sample output

42

7
222221 1

page10image18272

43

3
32 2



题意:

输入一个数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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值