1103 Integer Factorization(30 分)
作者: CHEN, Yue
单位: 浙江大学
时间限制: 1200 ms
内存限制: 64 MB
代码长度限制: 16 KB
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 (≤400), K (≤N) and P (1<P≤7). 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 122+42+22+22+12, or 112+62+22+22+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 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
这道题是找k-p因子,就是k个以p为指数的值加和为N就是 N的 K-P因子。
这道题首先的思路就是利用穷举法一个一个去穷举所有的可能,但是范围也是可以缩小的,那就是 1 ~ (为什么右边界是
,因为一旦数值超过了
那么
一定大于N)。
然后就是寻找接了,我们可以开一个vector<int> temp来记录解集,如果解符合条件,就将解保存下来 result = temp 。如果到达边界但是未能满足条件就去除刚刚加入到结尾的解。
题目中要求解如果有多个时,就选取底数和最大的作为解,如果解仍不唯一,那么就选取序列开始的值最大的(也即字典序最大)序列。底数和我们可以使用一个maxSum来记录,序列字典序最大我们可以倒序从 ~ 1去寻找解。
最后还要注意的是,因为一个数字的指数要使用好多次,最好在一开始的时候就将可能出现的值计算出来,然后再递归的时候直接使用,可以节省不少的时间。
另外在对一个浮点数值取整的时候,有时会发现与期待的值差1,这可能是由于浮点数自身表示缺陷的问题,可以将得到的浮点值+0.001 然后取整即可。(比如我在使用pow函数之后再去取整的时候每次都发现与期待的值不同)
AC代码:
#include <cstdio>
#include <math.h>
#include <vector>
using namespace std;
int n, k, p, maxfacSum = -1;
vector<int> temp, result;
int pownum[32];
void searchAns(int, int, int);
void init();
int power(int);
int main() {
scanf("%d%d%d", &n, &k, &p);
init();
int start = (int)(pow(n * 1.0, 1.0 / p) + 0.001);
searchAns(start, 0, 0);
if(result.size() == 0) {
printf("Impossible\n");
} else {
bool first = true;
printf("%d = ", n);
for(vector<int>::iterator it = result.begin(); it != result.end(); ++it) {
if(!first) {
printf(" + ");
}
printf("%d^%d", *it, p);
first = false;
}
}
return 0;
}
void searchAns(int num, int squSum, int facSum) {
if(squSum == n && facSum > maxfacSum && temp.size() == k) {
maxfacSum = facSum;
result = temp;
return ;
}
if(temp.size() >= k || squSum >= n || num < 1) {
return ;
}
temp.push_back(num);
int psqu = pownum[num];
searchAns(num, squSum + psqu, facSum + num);
temp.pop_back();
searchAns(num - 1, squSum, facSum);
}
void init() {
for(int i = 0; i < 32; ++i) {
pownum[i] = power(i);
}
}
int power(int a) {
int re = 1;
for(int i = 0; i < p; ++i) {
re *= a;
}
return re;
}
如有错误,欢迎指摘。