【PAT】1103 Integer Factorization(30 分)
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 (≤), K (≤) and P (1). 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, or 1, 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 { , } is said to be larger than { , } if there exists 1 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
C++代码如下:
1 #include<iostream> 2 #include<cmath> 3 #include<vector> 4 using namespace std; 5 6 int n, k, p; 7 vector<int>v; 8 vector<int>temp,ans; 9 int sum_g=0; 10 void init() { 11 int t; 12 for (int i = 0; i < 25; i++) { 13 t = pow(i, p); 14 if (t <= n) 15 v.push_back(t); 16 else break; 17 } 18 } 19 void DFS(int index, int sum, int nowk, int sumk) { 20 if ( nowk == k && sum == n) { 21 if (sumk > sum_g) { 22 sum_g = sumk; 23 ans = temp; 24 } 25 return; 26 } 27 if ( sum>n || nowk > k)return; 28 if (index - 1 >= 0) { 29 temp.push_back(index); 30 DFS(index , sum + v[index], nowk + 1, sumk + index); 31 temp.pop_back(); 32 DFS(index - 1, sum, nowk, sumk); 33 } 34 } 35 int main() { 36 cin >> n >> k >> p; 37 init(); 38 DFS(v.size() - 1, 0, 0, 0); 39 if (ans.size() > 0) { 40 cout << n << " = "; 41 for (int i = 0; i < ans.size() - 1; i++) 42 cout << ans[i] << "^" << p << " + "; 43 cout << ans[ans.size() - 1] << "^" << p << endl; 44 } 45 else 46 cout << "Impossible" << endl; 47 return 0; 48 }