zoukankan      html  css  js  c++  java
  • A1103 Integer Factorization (30分)(DFS)

    一、技术总结

    1. 这题是关于DFS即深度优先遍历算法,核心是掌握深度遍历算法的思想,也就是不断往下一个结点进行查找,如果查找不到,那么就返回;
    2. 关键点一个是递归边界,也就是查找不到的条件,以及能够往下查找的路有多少条;

    二、参考代码

    #include<iostream>
    #include<vector>
    #include<cmath>
    using namespace std;
    int n, k, p, maxFacSum = -1;
    vector<int> v, ans, tempAns;
    void init(){
    	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(tempK == k){
    		if(tempSum == n && facSum > maxFacSum){
    			ans = tempAns;
    			maxFacSum = facSum;
    		}
    		return;
    	}
    	while(index >= 1){
    		if(tempSum + v[index] <= n){
    			tempAns[tempK] = index;
    			dfs(index, tempSum + v[index], tempK + 1, facSum + index);
    		}
    		if(index == 1) return;
    		index--;
    	}
    }
    int main(){
    	scanf("%d%d%d", &n, &k, &p);
    	init();
    	tempAns.resize(k);
    	dfs(v.size() - 1, 0, 0, 0);
    	if(maxFacSum == -1){
    		printf("Impossible");
    		return 0;
    	}
    	printf("%d = ", n);
    	for(int i = 0; i < ans.size(); i++){
    		if(i != 0) printf(" + ");
    		printf("%d^%d", ans[i], p);
    	}
    	return 0;
    }
    
  • 相关阅读:
    Python--初识函数
    Python中的文件操作
    Python中的集合
    Python中的编码和解码
    Python的关键字is和==
    Python中的字典
    Python中的列表和元组
    Python中几种数据的常用内置方法
    Python的编码
    python_while
  • 原文地址:https://www.cnblogs.com/tsruixi/p/13226914.html
Copyright © 2011-2022 走看看