PAT甲级——A1103 Integer Factorization
The K−P factorization of a positive integer N is to write N as the sum of the P-th power of Kpositive 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
1 #include <iostream> 2 #include <vector> 3 #include <cmath> 4 #include <algorithm> 5 using namespace std; 6 int n, k, p, maxFacSum = -1;//maxFacSum用来记录最大底数之和 7 vector<int>fac, ans, temp;//最大底数不超过n的数,底数最优数序列,临时存放 8 void DFS(int index, int nowK, int sum, int facSum) 9 { 10 if (sum == n && nowK == k)//统计因素个数 11 { 12 if (facSum > maxFacSum)//更优的组合 13 { 14 ans = temp; 15 maxFacSum = facSum; 16 } 17 return; 18 } 19 if (sum > n || nowK > k)return;//超出限制 20 if (index - 1 >= 0)//给出数组小角标的限制 21 { 22 temp.push_back(index);//记录数据 23 DFS(index, nowK + 1, sum + fac[index], facSum + index);//选 24 temp.pop_back();//弹出数据 25 DFS(index - 1, nowK, sum, facSum);//不选 26 } 27 } 28 int main() 29 { 30 cin >> n >> k >> p; 31 for (int i = 0; pow(i, p) <= n; ++i) 32 fac.push_back(pow(i, p));//初始化底数不超过n的因素 33 DFS(fac.size() - 1, 0, 0, 0);//为了得到最大的因素数组,从最后一位开始向前搜索 34 if (maxFacSum == -1) 35 cout << "Impossible" << endl;//没有找到满足的序列 36 else 37 { 38 cout << n << " = "; 39 for (int i = 0; i < ans.size(); i++) 40 cout << ans[i] << "^" << p << (i == ans.size() - 1 ? "" : " + "); 41 } 42 return 0; 43 }