• 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;
    }
  • 相关阅读:
    footer在最低显示
    jQuery toast message 地址 使用
    linux 获取经过N层Nginx转发的访问来源真实IP
    Java Json格式的字符串转变对象
    多个机器获取微信access-token导致的有效性问题
    站点技术---301重定向
    C++技术问题总结-第8篇 STL内存池是怎么实现的
    IIS中遇到无法预览的问题(HTTP 错误 401.3
    梯度下降深入浅出
    COM-IE-(2)
  • 原文地址:https://www.cnblogs.com/littlepage/p/12900517.html
Copyright © 2020-2023  润新知