PAT 1103 Integer Factorization (30 分) DFS+剪枝(important)

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int n,k,p,maxFacSum=-1;
vector<int> v, ans, tempAns;   //tempAns为当前深度优先遍历⽽来的序列
void init(){
    int temp=0,index=1;
    while(temp<=n){
        v.push_back(temp);
        temp=pow(index,p);
        index++;
    }
}
void dfs(int index, int tempSum, int tempK, int facSum){    //记录当前正在相加的index(即v[i]的i的值),当前的总和tempSum,当前K的总个数tempK,facSum为当前因⼦的和,让它和maxFacSum⽐较
    //递归终止条件
    if(tempK==k){                                   //选择第k个数了
        if (tempSum == n && facSum > maxFacSum) {  //tempK==K且tempSum=n的时候看是否更新序列
            ans = tempAns;
            maxFacSum = facSum;
        }
        return;             //tempK==K但是tempSum!=n的时候需要剪枝
    }
    //递归选择主体
    while(index>=1){
        if(tempSum+v[index]<=n){   //当且仅当tempSum + v[index] <= n时,进⾏下⼀层的DFS,⽽不要进⼊下⼀层DFS发现不满⾜条件再返回,这样开销会⽐较⼤~
            tempAns[tempK]=index;
            dfs(index, tempSum + v[index], tempK + 1, facSum + index);
        }
        if(index==1) return;       //在枚举的时候,按顺序枚举,上界或者下界可进⾏剪枝,index=1已经不能--
        index--;
    }
}
int main() {   
    cin>>n>>k>>p;
    init();
    tempAns.resize(k);
    dfs(v.size() - 1, 0, 0, 0);
        if (maxFacSum == -1) {
        printf("Impossible");
        system("pause");
        return 0;
    }
    printf("%d = ", n);
    for (int i = 0; i < ans.size(); i++) {
        if (i != 0) printf(" + ");
        printf("%d^%d", ans[i], p);
    }
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值