1103. Integer Factorization (30)【搜索+剪枝】——PAT (Advanced Level) Practise


題目信息

1103. Integer Factorization (30)

時間限制1200 ms
內存限制65536 kB
代碼長度限制16000 B
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

解題思路

搜索加剪枝

AC代碼

#include <cstdio>
#include <cstring>
#include <cmath>
#include <functional>
#include <algorithm>
using namespace std;
int rmx = -1, rs[405], trs[405], pw[22];
int n, k, p, has = 0;

void find(int t, int lit, int loc, int sum){
if (t == 0 && loc > k){
if (sum > rmx){
rmx = sum;
memcpy(rs, trs, sizeof(rs));
}
has = 1;
}
if (loc > k) return;
for (int i = lit; i >= 1; --i){
if (pw[i] <= t - (k - loc) && pw[i] * (k - loc + 1) >= t){ //剪枝
trs[loc] = i;
find(t - pw[i], i, loc + 1, sum + i);
}
}
}
int main()
{
scanf("%d%d%d", &n, &k, &p);
for (int i = 0; i < 21; ++i){
pw[i] = (int)(pow(i, p) + 0.1);
}
find(n, 20, 1, 0);
if (has){
printf("%d = %d^%d", n, rs[1], p);
for (int i = 2; i <= k; ++i){
printf(" + %d^%d", rs[i], p);
}
printf("\n");
}else {
printf("Impossible\n");
}
return 0;
}

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com