题目
The K − P K−P K−P factorization of a positive integer N N N is to write N N N as the sum of the P P P-th power of K K K positive integers. You are supposed to write a program to find the K − P K−P K−P factorization of N N N for any positive integers N N N, K K K and P P P.
Input Specification:
Each input file contains one test case which gives in a line the three positive integers N ( ≤ 400 ) N(\le400) N(≤400), K ( ≤ N ) K(\le N) K(≤N) and P ( 1 < P ≤ 7 ) P(1\lt P\le7) P(1<P≤7). The numbers in a line are separated by a space.
Output Specification:
For each case, if the solution exists, output in the format:
N = n[1]^P + … n[K]^P
where n[i]
(i = 1
, …, K
) is the i
-th factor. All the factors must be printed in non-increasing order.
Note: the solution may not be unique. For example, the 5-2 factorization of 169 has 9 solutions, such as
1
2
2
+
4
2
+
2
2
+
2
2
+
1
2
12^2+4^2+2^2+2^2+1^2
122+42+22+22+12, or
1
1
2
+
6
2
+
2
2
+
2
2
+
2
2
11^2+6^2+2^2+2^2+2^2
112+62+22+22+22
, or more. You must output the one with the maximum sum of the factors. If there is a tie, the largest factor sequence must be chosen – sequence {
a
1
,
a
2
,
⋯
,
a
K
a_1,a_2,⋯,a_K
a1,a2,⋯,aK} is said to be larger than {
b
1
,
b
2
,
⋯
,
b
K
b_1,b_2,⋯,b_K
b1,b2,⋯,bK} if there exists
1
≤
L
≤
K
1\le L\le K
1≤L≤K such that
a
i
=
b
i
a_i=b_i
ai=bi for
i
<
L
i\lt L
i<L and
a
L
>
b
L
a_L\gt b_L
aL>bL.
If there is no solution, simple output Impossible
.
Sample Input 1:
169 5 2
Sample Output 1:
169 = 6^2 + 6^2 + 6^2 + 6^2 + 5^2
Sample Input 2:
169 167 3
Sample Output 2:
Impossible
题目大意
求 k k k个数的 p p p次幂之和等于 N N N。答案可能有多种,输出 k k k个数之和最大的那种,若和最大则输出字典序最大的。
思路
n
n
n最大为400,所以不必要从
n
n
n开始往下枚举,只需枚举a[i]
从1开始递增,使得a[i]^p <= n
, 将i的P次幂存储到vector
中,然后 DFS 搜索。
代码
#include <iostream>
#include <cstdio>
#include <vector>
#include <cmath>
using namespace std;
int n, k, p;
vector<int> e;
vector<int> ans, tempaans;
int sum = 0, tempsum = 0, temptotal = 0;
int getExp(int t){
int res = 1;
for(int i=0; i<p; i++)
res *= t;
return res;
}
void dfs(int t){
if(temptotal > n || tempaans.size() > k)
return;
if(temptotal == n && tempaans.size() == k && tempsum > sum){
//printf("%d %d\n", tempsum, temptotal);
sum = tempsum;
ans = tempaans;
return;
}
for(int i=t; i>0; i--){
tempsum += i, temptotal += e[i], tempaans.push_back(i);
dfs(i);
tempsum -= i, temptotal -= e[i], tempaans.pop_back();
}
}
int main(){
scanf("%d%d%d", &n, &k, &p);
for(int i=0; ; i++){
e.push_back(getExp(i));
if(getExp(i+1) > n){
dfs(i);
break;
}
}
if(ans.empty())
printf("Impossible\n");
else{
printf("%d = %d^%d", n, ans[0], p);
for(int i=1; i<k; i++)
printf(" + %d^%d", ans[i], p);
printf("\n");
}
return 0;
}