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+剪枝)
36 0
Find The Multiple(dfs和bfs都可)
Find The Multiple(dfs和bfs都可)
24 0
|
Go
LeetCode 124. Binary Tree Maximum Path Sum
给定一个非空二叉树,返回其最大路径和。 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
65 0
LeetCode 124. Binary Tree Maximum Path Sum
CF711D-Directed Roads(组合数学 dfs找环)
CF711D-Directed Roads(组合数学 dfs找环)
80 0
CF711D-Directed Roads(组合数学 dfs找环)
codeforces1244——D.Paint the Tree(dfs)
codeforces1244——D.Paint the Tree(dfs)
81 0
|
人工智能
codeforces 1092——F:Tree with Maximum Cost (树上DP)
codeforces 1092——F:Tree with Maximum Cost (树上DP)
112 0
AtCoder--755——dfs
题目描述 You are given an integer N. Among the integers between 1 and N (inclusive), how many Shichi-Go-San numbers (literally “Seven-Five-Three numbers”) are there? Here, a Shichi-Go-San number is a positive integer that satisfies the following condition:
95 0
Leetcode-Medium 416. Partition Equal Subset Sum
Leetcode-Medium 416. Partition Equal Subset Sum
115 0
【1103】Integer Factorization (DFS)
(1)开一个vector数组fac存0^ p ,1^ p… i ^ p. (2)DFS: 分叉口:利用DFS对fac[index]进行选择,有“选”与“不选”两种选择,如果不选,则把问题转化为对fac[index]进行选择;如果选择,由于每个数字可以重复选择即下一次还能选择fac[index]。 递归边界:2个return,第一个满足sum == N且nowK==
113 0
【1103】Integer Factorization (30分)【DFS】
【1103】Integer Factorization (30分)【DFS】 【1103】Integer Factorization (30分)【DFS】
86 0