The K-P factorization of a positive integer N is to write N as the sum of the P-th power of K positive integers. You are supposed to write a program to find the K-P factorization of N for any positive integers N, K and P.

Input Specification:

Each input file contains one test case which gives in a line the three positive integers N (<=400), K (<=N) and 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 = n1^P + ... nK^P

where ni (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 122 + 42 + 22 + 22 + 12, or 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 { a1, a2, ... aK } is said to be larger than { b1, b2, ... bK } if there exists 1<=L<=K such that ai=bi for i<L and 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

 1 #include <iostream>
 2 #include <cmath>
 3 #include <numeric>
 4 #include <vector>
 5 using namespace std;
 6 int N, K, P, POW[22], optSum; 
 7 vector<int> opt, temp;
 8 
 9 void dfs(int start, int val, int sum){
10     if(temp.size() > K || val > N || start == 0)    return; 
11     if(val == N && temp.size() == K){//满足条件 
12         if(opt.size() == 0)    opt = temp, optSum = sum;//第一次得到满足条件的序列 
13         else{
14             if(sum > optSum)    opt = temp, optSum = sum;
15             else if(optSum == sum && temp > opt)    opt = temp;
16         }
17         return;
18     }
19     temp.push_back(start);
20     dfs(start, val+POW[start], sum + start);//
21     temp.pop_back();
22     dfs(start-1, val, sum); //不选 
23 }
24 
25 void print(vector<int> &v){
26     printf("%d = ", N);
27     for(int i = 0; i < v.size(); ++  i){
28         printf("%d^%d", v[i], P);
29         if(i != v.size()-1)    printf(" + ");
30     }
31 }
32 
33 int main()
34 {
35     scanf("%d%d%d", &N, &K, &P);
36     int x = sqrt(N)+1;
37     for(int i = 1; i <= x; i ++){//打表 
38         POW[i] = pow(i, P);
39     }
40     dfs(x, 0, 0);
41     if(opt.size() == 0)    printf("Impossible\n");
42     else print(opt);
43     return 0;
44 }

 

Posted on 2017-02-28 15:56  小小旅行商  阅读(86)  评论(0编辑  收藏  举报