大意:将整数N分成K个正整数的P次幂之和。 N (≤400), K (≤N) and P (1<P≤7).
- 想到dfs的树形结构,并以想到现场的还原
- 要求字典序大,倒序从大的开始选择即可
#include<bits/stdc++.h>
#define f(i,a,b) for(int i=a;i<=b;++i)
#define fd(i,a,b) for(int i=a;i>=b;--i)
using namespace std;
const int N = 1e5 + 50;
int n, k, p;
vector<int> fac;//可选物品
vector<int> res;//答案序列,要求字典序大?,先选大的
vector<int> stk;//dfs答案栈
int power(int x) {
int res = 1;
f(i, 1, p)res = res * x;
return res;
}
void getfac() {
int id = 1,x=id;
while ( x<= n) {
fac.emplace_back(x);
x = power(++id);
}
}
int resw = 0;
void dfs(int idx, int v, int num, int w) {
if (idx < 0)return;
if (v == n && num == k) {
if (w > resw) {
resw = w;
res = stk;
}
}
if (v > n || num > k)return;//走下去已经没有意义
stk.emplace_back(idx+1);
dfs(idx, v + fac[idx], num + 1, w + idx + 1);
stk.pop_back();
dfs(idx - 1, v, num, w);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif
cin >> n >> k >> p;
getfac();
dfs(fac.size() - 1, 0, 0,0);
if (resw) {
//169 = 6^2 + 6^2 + 6^2 + 6^2 + 5^2
cout << n << " = ";
int fg = 0;
for (auto i : res) {
if (fg)cout << " + " << i << "^" << p;
else fg++, cout << i << "^" << p;
}
cout << endl;
}
else puts("Impossible");
return 0;
}