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;
    }
  • 相关阅读:
    python--模块与包
    内置函数 的总结
    迭代器 生成器 列表推导式 生成器表达式的一些总结
    函数的有用信息 带参数的装饰器 多个装饰器装饰一个函数
    函数名的应用(第一对象) 闭包 装饰器
    动态参数 名称空间 作用域 作用域链 加载顺序 函数的嵌套 global nonlocal 等的用法总结
    函数的初识 函数的返回值 参数
    文件操作 常用操作方法 文件的修改
    遍历字典的集中方法 集合的作用 以及增删查的方法
    计算机硬件的小知识
  • 原文地址:https://www.cnblogs.com/littlepage/p/12900517.html
Copyright © 2011-2022 走看看