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.
输入格式
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.
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.
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 12 2 12^{2} 122+ 4 2 4^{2} 42+ 2 2 2^{2} 22+ 2 2 2^{2} 22+ 1 2 1^{2} 12, or 11 2 11^{2} 112+ 6 2 6^{2} 62+ 2 2 2^{2} 22+ 2 2 2^{2} 22+ 2 2 2^{2} 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:
169 5 2
Sample Output:
169 = 6^2 + 6^2 + 6^2 + 6^2 + 5^2
总结
- 这题先要把题目读明白,题目要找的是给定一个N,然后要输出K个数,使N= a 1 p a_1^{p} a1p+ a 2 p a_2^{p} a2p+…+ a k p a_k^{p} akp,如果有多个解则选择 a 1 + a 2 + . . . + a k a_1+a_2+...+a_k a1+a2+...+ak最大的解,若还有多个解则找到字典序最大的解(也就是说, 题目给的 12 2 12^{2} 122+ 4 2 4^{2} 42+ 2 2 2^{2} 22+ 2 2 2^{2} 22+ 1 2 1^{2} 12字典序比 11 2 11^{2} 112+ 6 2 6^{2} 62+ 2 2 2^{2} 22+ 2 2 2^{2} 22+ 2 2 2^{2} 22的字典序要大)
- 不妨把 n p n^{p} np都存入到一个数组fac中,这样的话就变成了在这个数组里面找k个数,使得其和等于N,并且从底数最大的开始找(因为这样默认的话字典序最大)
- 用深度优先搜索解决此问题,index为fac数组中的下标,nowK为选择的个数,sum为当前选的个数和,facSum为底数和。递归出口有两个:一个是其个数满足k且和为N时,另一个出口是sum过大 或 下标越界 或 选择的底数大于等于k。
- 在进行递归时,只有两种方案,一种是选择当前的底数,另一种是不选择当前的底数。若选择了当前的底数,则需要把当前的数存放到一个temp数组中去,并进入下层递归时修改对应的参数,递归完毕时将该底数出栈,寻求另外的解。若不选择当前的数,只修改序号,其他参数不变。
AC代码
#include <iostream>
#include<vector>
#include<math.h>
using namespace std;
int n, k, p, fac[30], num = 0, maxFacSum = -1;
vector<int> temp, ans;
void DFS(int index, int nowK, int sum, int facSum) {
if (nowK == k && sum == n) {
if (facSum > maxFacSum) {
maxFacSum = facSum;
ans = temp;
}
return;
}
if (index < 1 || nowK >= k || sum >= n) return;
//选择当前因子
temp.push_back(index);
DFS(index, nowK + 1, sum + fac[index], facSum + index);
temp.pop_back();
DFS(index - 1, nowK, sum, facSum); //不选当前因子
}
int main() {
scanf("%d %d %d", &n, &k, &p);
while (pow(num, p) <= n) { //计算p次方
fac[num] = pow(num, p);
num++;
}
DFS(num-1, 0, 0, 0);
if(maxFacSum==-1) printf("Impossible\n");
else {
printf("%d = %d^%d", n, ans[0], p);
for (int i = 1; i < ans.size(); i++) {
printf(" + %d^%d", ans[i], p);
}
printf("\n");
}
return 0;
}