1103. Integer Factorization (30) dfs

简介: #include #include #include using namespace std;int n, k, p, maxFacSum = -1; // n 和 k 几个数字 p阶数vector v, ...


#include <iostream>
#include <cmath>
#include <vector>
using namespace std;

int n, k, p, maxFacSum = -1; // n 和  k 几个数字 p阶数
vector<int> v, ans, tempAns;

void init(){//将1到n的每一p次方都存储 减少计算量
    int temp = 0, index = 1;
    while(temp <= n){
        v.push_back(temp);
        temp = pow(index, p);
        index++;
    }
}

void dfs(int index, int tempSum, int tempK, int facSum){
    if (tempSum == n && tempK == k) {//递归终止条件
        if (facSum > maxFacSum) {//条件选取最大的Sum
            ans = tempAns;
            maxFacSum = facSum;
        }
        return;
    }
    if(tempSum > n || tempK > k) return; //循环终止条件
    if (index >= 1) {//以下过程一直持续到 index = 1
        tempAns.push_back(index);//0
        dfs(index, tempSum + v[index], tempK + 1, facSum + index);//首先递归调用index
        tempAns.pop_back();//不满足条件 删除最后一个元素
        dfs(index - 1, tempSum, tempK, facSum);//再递归调用index-1
    }
}

int main(int argc, const char * argv[]) {
    cin >> n >> k >> p;
    init();
    dfs((int)v.size() - 1, 0, 0, 0);
    if (maxFacSum == -1) {
        cout << "Impossible\n";
        return 0;
    }
    cout << n << " = ";
    for (int i = 0; i < ans.size(); i++) {
        if(i != 0) cout << " + ";
        cout << ans[i] << "^" << p;
    }
    cout << endl;

    return 0;
}

目录
相关文章
Biggest Number (DFS+剪枝)
Biggest Number (DFS+剪枝)
42 0
Find The Multiple(dfs和bfs都可)
Find The Multiple(dfs和bfs都可)
28 0
|
Go
LeetCode 124. Binary Tree Maximum Path Sum
给定一个非空二叉树,返回其最大路径和。 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
70 0
LeetCode 124. Binary Tree Maximum Path Sum
LeetCode 152. Maximum Product Subarray
给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
50 0
LeetCode 152. Maximum Product Subarray
CF711D-Directed Roads(组合数学 dfs找环)
CF711D-Directed Roads(组合数学 dfs找环)
86 0
CF711D-Directed Roads(组合数学 dfs找环)
codeforces1244——D.Paint the Tree(dfs)
codeforces1244——D.Paint the Tree(dfs)
87 0
|
人工智能 vr&ar
Atcoder--Candy Distribution II--前缀和+map
题目描述 There are N boxes arranged in a row from left to right. The i-th box from the left contains Ai candies. You will take out the candies from some consecutive boxes and distribute them evenly to M children. Such being the case, find the number of the pairs (l,r) that satisfy the following:
104 0
Leetcode-Medium 416. Partition Equal Subset Sum
Leetcode-Medium 416. Partition Equal Subset Sum
124 0
Leetcode-Medium 152. Maximum Product Subarray
Leetcode-Medium 152. Maximum Product Subarray
117 0
|
Java Python
Leetcode-Medium 494. Target Sum
Leetcode-Medium 494. Target Sum
90 0