A1103. Integer Factorization (30)

The K-P factorization of a positive integer N is to write N as the sum of the P-th power of K positive integers. You are supposed to write a program to find the K-P factorization of N for any positive integers N, K and P.

Input Specification:

Each input file contains one test case which gives in a line the three positive integers N (<=400), K (<=N) and P (1

思路:
  • void DFS(int index,int nowk,int sum,int facSum){}
    当前处理的fac几号位,记为index.已经选了几个数,记为nowk,记录当前选出的数底数和为sum,当前选出的数底数和facSum

  • 开一个vector< int >fac,存放所有不超过N的n^p,为了对应把0也存放进去。vector< int>ans存放最优底数序列,vector< int>temp存放当前选中的底数序列

  • 注意输出格式,=前有空格,然后” + “有两个空格。

#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
int n,k,p,i,maxFacSum=-1;//最大底数和
vector<int> fac,ans,temp;
//fac记录最优底数序列,temp存放递归中的临时底数序列。fac记录0^p,1^p,````i^p
int power(int x)//算x^n
{
    int ans=1;
    for ( i=0;i<p;i++)
        ans=ans*x;
    return ans;
}
void init()//写fac
{
    int j=0;
    int temp=0;
    while(temp<=n){
        fac.push_back(temp);
        temp=power(++j);
    }
}
void DFS(int index,int nowk,int sum,int facSum)
{
    //当前访问fac[index],nowk 选中个数,sum选中数的和,facSum选中底数和
    if(sum==n&&nowk==k)
    {
        if(facSum>maxFacSum)
        {
            ans=temp;
            maxFacSum=facSum;
        }
        return;
    }
    if(sum>n||nowk>k)return;
    if(index-1>=0)
    {   //fac[0]不需要选择
        temp.push_back(index);
        DFS(index,nowk+1,sum+fac[index],facSum+index);
        temp.pop_back();
        DFS(index-1,nowk,sum,facSum);

    }
}
int main()
{
    scanf("%d%d%d",&n,&k,&p)    ;
    init();
    DFS(fac.size()-1,0,0,0);
    if(maxFacSum==-1)printf("Impossible\n");
    else{
        printf("%d = %d^%d",n,ans[0],p);
        for(i=1;i<ans.size();i++)
        {
            printf(" + %d^%d",ans[i],p);
        }
        printf("\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值