码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-05-18 19:29:49      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

题目信息

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

标签:

原文地址:http://blog.csdn.net/xianyun2009/article/details/51407919

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!