#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;
}
PAT 1103 Integer Factorization (30 分) DFS+剪枝(important)
最新推荐文章于 2022-03-22 12:26:36 发布