Cubes dfs+剪枝

Write a program that takes a natural number N and decomposes it as a sum of the minimum number of exact 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 minimum number of natural cubes. The second line contains k space-separated natural numbers - that raised to the power of 3 sum to N.

42
7
2 2 2 2 2 1 1

43
3
3 2 2

/*
    数字最大不超过356,路径不会超过50(10左右),每次为了保证序列为递增的,dfs更新起点nu
*/
#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>
#include<cctype>
#include<queue>
#include<set>
#include<cstdlib>
#include<ctime>
#include<algorithm>
#include<cmath>
#include<assert.h>
using namespace std;
typedef long long LL;
const int maxn=400;
const int INF=44777449;
int ans[maxn];
int A[maxn],a[maxn];
int cnt=50,N;

void init()
{
    for(int i=1; i<maxn; i++)
    {
        A[i]=i*i*i;
    }
}

void dfs(int d,int n,int nu)
{
    if(n==0){
        for(int i=1;i<=d;i++){              //循环结束,记录答案,输出路径
            ans[i]=a[i];
        }
        cnt=d;                              //记录路径长度,也可以作为返回结束标志
    }
    if(d+1>=cnt||d+n/A[nu]>=cnt)            //结束标志
        return;
    for(int i=nu;i>=1;i--){                 //更新dfs的起点
        if(n-A[i]>=0){
            a[d+1]=i;                       //记录路径
            dfs(d+1,n-A[i],i);              //dfs下一条可能的节点
        }
    }
}


int main()
{
    init();
    cin>>N;
    dfs(0,N,360);
    cout<<cnt<<endl;
    for(int i=1;i<=cnt;i++){
        cout<<ans[i]<<" ";
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值