本文同步發布在CSDN:https://blog.csdn.net/weixin_44385565/article/details/90574720
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.
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.
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=bifor i<L and aL>bL.
If there is no solution, simple output Impossible
.
169 5 2
169 = 6^2 + 6^2 + 6^2 + 6^2 + 5^2
169 167 3
Impossible
題目大意:將一個正整數N分解成K個正整數的P次方和,在多個結果里面找出因子之和最大的,若因子之和相同,字典序大的為答案。
思路:主要是DFS的思想,建立一個數組F,用來儲存 1~m的P次方,m^P為≤N的最大正整數。find()里面傳入四個變量,n為當前find()里面的for循環次數;cnt初始值為K,cnt=0作為遞歸的邊界;tmpSum儲存因子之和;sum是總和,sum=N才是符合條件的備選答案~
下一層的遞歸里的n總是小於等於上一層遞歸里的n,所以保證了字典序,不需要畫蛇添足地寫compera函數來篩選答案了(一開始就是因為這個操作導致測試點2答案錯誤),若無必要,勿增操作。
1 #include <iostream> 2 #include <vector> 3 #include <cmath> 4 using namespace std; 5 int N, K, P, m, fSum = -1; 6 vector <int> ans, F, tmpA; 7 void find(int n,int cnt, int tmpSum, int sum); 8 9 int main() 10 { 11 scanf("%d%d%d", &N, &K, &P); 12 int i = 1; 13 F.push_back(0); 14 while (1) { 15 int x = pow(i, P); 16 if (x > N) 17 break; 18 else { 19 F.push_back(x); 20 i++; 21 } 22 } 23 m = F.size() - 1; 24 find(m, K, 0, 0); 25 if (ans.empty()) { 26 printf("Impossible\n"); 27 return 0; 28 } 29 printf("%d =", N); 30 for (int i = 0; i < K; i++) { 31 printf(" %d^%d", ans[i], P); 32 if (i < K - 1) { 33 printf(" +"); 34 } 35 } 36 printf("\n"); 37 return 0; 38 } 39 void find(int n, int cnt, int tmpSum, int sum) { 40 if(n==0) return; 41 if (cnt == 0) { 42 if (fSum < tmpSum) { 43 if (sum == N) { 44 ans = tmpA; 45 fSum = tmpSum; 46 } 47 } 48 return; 49 } 50 for (int i = n; i > 0; i--) { 51 if (sum <= N) { 52 tmpA.push_back(i); 53 find(i, cnt - 1, tmpSum + i, sum + F[i]); 54 tmpA.pop_back(); 55 } 56 } 57 }
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。