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

Posted 闲云阁

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}

以上是关于1103. Integer Factorization (30)搜索+剪枝——PAT (Advanced Level) Practise的主要内容,如果未能解决你的问题,请参考以下文章

PAT甲级1103 Integer Factorization (30分)

PAT 1103 Integer Factorization[难]

1103 Integer Factorization

PAT 1103 Integer Factorization

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

1103 Integer Factorization