1103 Integer Factorization (DFS)
The K−P 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 K−Pfactorization 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问题关键:参数的选取问题(要考虑最优解的比较),边界条件判断
此处让node从大到小顺序选择,就可以尽早选中字典序高的
而DFS中第四个参数的选择是让多方案判断时的时间复杂度为O(1)
#include<cstdio> #include<cmath> #include<vector> #include<algorithm> using namespace std; vector<int> fac,res,temp; int n,k,p,maxfac=-1;//记录最大底数和,判断最优 void init(){//预处理fac数组 for(int i=0;i<=n;i++){ if(pow(i,p)>n) break; fac.push_back(pow(i,p)); } } void DFS(int node,int sum,int num,int max){ //节点下标,选数和,选数量, 底数和 if(sum==n&&num==k){ if(max>maxfac) { res=temp; maxfac=max; } return; } else if(node<1||sum>n||num>k) return; else{//对于可重复选取问题,先走选分支 temp.push_back(node); DFS(node,sum+fac[node],num+1,max+node); temp.pop_back(); DFS(node-1,sum,num,max); } } int main(){ scanf("%d %d %d",&n,&k,&p); init(); DFS(fac.size()-1,0,0,0); if(maxfac==-1) printf("Impossible\n"); else{ printf("%d = %d^%d",n,res[0],p); for(int i=1;i<res.size();i++) printf(" + %d^%d",res[i],p); } return 0; }