1103 Integer Factorization (30分)

The KP 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 KP 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 (≤), K (≤) and P (1). 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 1, or 1, 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 { , } is said to be larger than { , } if there exists 1 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

参照柳婼大佬的博客, dfs+剪枝,呀呀呀,dfs老学不会。

#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int N, K, P, maxFacSum = -1;
vector<int> v, ans, tmpAns;
void init() {
    int tmp = 0, index = 1;
    while(tmp <= N) {
        v.push_back(tmp);
        tmp = pow(index++, P);
    }
}
void dfs(int index, int tmpSum, int tmpK, int facSum) {
    if(tmpK == K) {
        if(tmpSum == N && facSum > maxFacSum) {
            ans = tmpAns;
            maxFacSum = facSum;
        }
        return;
    }
    while(index >= 1) {
        if(tmpSum + v[index] <= N) {
            tmpAns[tmpK] = index;
            dfs(index, tmpSum + v[index], tmpK + 1, facSum + index);
        } 
        if(index == 1) return;
        index--;
    }

}
int main() {
    scanf("%d%d%d", &N, &K, &P);
    init();
    tmpAns.resize(K);
    dfs(v.size() - 1, 0, 0, 0);
    if(maxFacSum == -1) printf("Impossible");
    else {
        printf("%d = ", N);
        for(int i = 0; i < ans.size(); i++) {
            if(i != 0) printf(" + ");
            printf("%d^%d", ans[i], P);
        }
    }
    return 0;
}

 

posted @ 2020-05-16 14:52  SteveYu  阅读(180)  评论(0编辑  收藏  举报