PAT A1103
标签(空格分隔): PAT
解题思路: DFS
#include <cstdio>
#include <vector>
using namespace std;
int n, k, p;
int maxFacSum = -1; //记录最大因子和
vector<int> ans, temp, fac;
int power(int x) {
int ans = 1;
for(int i = 0; i < p; i++) {
ans *= x;
}
return ans;
}
void init() {
int i = 0, temp = 0; //初始化fac,把因子的平方存入其中
while(temp <= n) {
fac.push_back(temp);
temp = power(++i);
}
}
void DFS(int index, int nowK, int sum, int facSum) {
if(nowK == k && sum == n) { //dfs终止条件
if(facSum > maxFacSum) { //目前的因子和大于最大因子和
maxFacSum = facSum;
ans = temp; //更新答案vector
}
return;
}
if(nowK > k || sum > n) return; //此时不可能满足条件,直接返回
if(index - 1 >= 0) {
temp.push_back(index);
DFS(index, nowK + 1, sum + fac[index], facSum + index); //选择index
temp.pop_back();
DFS(index - 1, nowK, sum, facSum); //不选index
}
}
int main() {
scanf("%d%d%d", &n, &k, &p);
init();
DFS(fac.size() - 1, 0, 0, 0);
if(maxFacSum == -1) printf("Impossible
");
else {
printf("%d = %d^%d", n, ans[0], p);
for(int i = 1; i < ans.size(); i++) {
printf((" + %d^%d"), ans[i], p);
}
}
return 0;
}