其他分享
首页 > 其他分享> > PAT A1103 Integer Factorization (30 分)——dfs,递归

PAT A1103 Integer Factorization (30 分)——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−P factorization 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 (≤400), K (≤N) and P (1<P≤7). 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 12​2​​+4​2​​+2​2​​+2​2​​+1​2​​, or 11​2​​+6​2​​+2​2​​+2​2​​+2​2​​, 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 { a​1​​,a​2​​,⋯,a​K​​ } is said to be larger than { b​1​​,b​2​​,⋯,b​K​​ } if there exists 1≤L≤K 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
 
 1 #include <stdio.h>
 2 #include <algorithm>
 3 #include <set>
 4 #include <string.h>
 5 #include <vector>
 6 #include <math.h>
 7 #include <queue>
 8 using namespace std;
 9 bool cmp(int a,int b){
10     return a>b;
11 }
12 const int maxn = 411;
13 int n,p,k,maxk=-1;
14 int vis[maxn]={0};
15 vector<int> res,tmp;
16 void dfs(int index,int ksum,int cntk,int nsum){
17     //if(index<1 || nsum>n || cntk>k) return;
18     if(nsum==n && cntk == k){
19         if(ksum>maxk){
20             res=tmp;
21             maxk=ksum;
22         }
23         return;
24     }
25     tmp.push_back(index);
26     if(nsum+vis[index]<=n && cntk+1<=k)dfs(index,ksum+index,cntk+1,nsum+vis[index]);
27     tmp.pop_back();
28     if(index-1>0)dfs(index-1,ksum,cntk,nsum);
29 }
30 int main(){
31     scanf("%d %d %d",&n,&k,&p);
32     int i;
33     for(i=1;i<=n;i++){
34         int res = pow(i,p);
35         if(res>n)break;
36         vis[i]=res;
37     }
38     i--;
39     dfs(i,0,0,0);
40     if(maxk==-1)printf("Impossible");
41     else{
42         printf("%d = ",n);
43         sort(res.begin(),res.end(),cmp);
44         for(int j=0;j<res.size();j++){
45             printf("%d^%d",res[j],p);
46             if(j<res.size()-1)printf(" + ");
47         }
48     }
49 }
View Code

注意点:看到题目想到了要从大到小一个个遍历然后去比较条件,想用while和for写出来,发现真的写不来,有好多情况,看了大佬的思路,原来这就是递归,很明显的有个递归边界,递归式也很方便,果然对递归的理解还是不够深,知道思路,却没想到用递归这个武器。

标签:index,PAT,递归,int,res,30,cntk,dfs,include
来源: https://www.cnblogs.com/tccbj/p/10450273.html