1. 程式人生 > >1103 Integer Factorization (DFS)

1103 Integer Factorization (DFS)

text sample number and form separate ups power ges

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 a?i??=b?i?? for i<L and a?L??>b?L??.

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; }

1103 Integer Factorization (DFS)