PAT (Advanced Level) Practice 1103 Integer Factorization

回溯就可以解,记一个坑,在计算a的n次方时,如果你需要的是整数,最好不要用pow,而是自己写一个。

我的编译器使用pow的时候,如果传的值不是double类型的而是int类型的数值,会产生比较大的误差,如10的2次方可能的出的结果就是99,而非100。 

还有,自己写的pows不会超时,而使用pow函数会有个测试点超时。

#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int n,k,p,m,maxn=-999;
vector<int> temp,result;
int pows(int a,int e){
    int sum =1;
    while(e!=0){
        sum=sum*a;
        e--;
    }
    return sum;
}
void f(int i){
    if(k<0) return;
    if(k==0&&n==0){
        bool larger=false;
        int sum=0;
        for(int j=0;j<temp.size();j++){
            sum+=temp[j];
            if(result.size()!=0&&temp[j]>result[j]) larger=true;
        }
        if(sum>maxn ||(sum==maxn&&larger)){
            result=temp;
            maxn=sum;
        }
        return;
    }
    for(int h=i;h<=m;h++){
        int facor=pows(h,p);
        if(n-facor>=0){
            n-=facor;
            k--;
            temp.push_back(h);
            f(h);
            temp.pop_back();
            n+=facor;
            k++;
        }else{
            return;
        }
    }
}
int main()
{
    cin>>n>>k>>p;
    int tn=n;
    for(int i=1;i<=n;i++){
        if(pows(i,p)>=n){
            m=i;//阈值
            break;
        }
    }
    f(1);
    if(result.size()==0){
        cout<<"Impossible"<<endl;
    }else{
        cout<<tn<<" = ";
        for(int i=result.size()-1;i>=0;i--){
            cout<<result[i]<<"^"<<p;
            if(i!=0){
                cout<<" + ";
            }
        }
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值