PAT甲級——1103 Integer Factorization (DFS)

1103 Integer Factorization (30 分)

The

Input Specification:

Each input file contains one test case which gives in a line the three positive integers

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

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 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 }