zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    Linux XZ格式的解压
    Linux eject弹出光驱
    什么是错误链接/死链接
    什么是相对地址和绝对地址
    网站被K或者降权后应该如何恢复
    网络营销怎么做才有“钱”途
    如何通过seo技术提高网站对用户的友好度
    如何利用微博客进行seo赚钱营销
    做SEO必须制定超越竞争对手网站的方案
    文章很快收录后又被删除的原因
  • 原文地址:https://www.cnblogs.com/littlepage/p/12900517.html
Copyright © 2011-2022 走看看