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 122 +42 +22 +22 +12 , or 112 +62 +22 +22 +22 , 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 { a1 ,a2 ,⋯,aK } is said to be larger than { b1 ,b2 ,⋯,bK } if there exists 1≤L≤K 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
题意:
给定正整数N、K、P,将N表示成K个正整数(可以相同,递减排列)的P次方的和, 即N = n1^P + …nK^P。如果有多种方案,那么选择底数和ni+…+ nK最大的方案;如果还有多种方案,那么选择底数序列的字典序最大的方案。
思路:
①利用DFS进行枚举,K个正整数范围均在 1~
之间,每次都枚举
个必定会超时。
②首先初步剪枝,DFS每次记录N还剩余多少,当N<=0或者已选全满K个正整数时return; 。
③因为只需要选择出其中一种方案,那就会存在一些没有必要的枚举。
如样例1:6 6 6 6 5 ,在上述实际枚举过程中,会出现5 6 6 6 6,6 5 6 6 6,6 6 5 6 6,6 6 6 5 6,6 6 6 6 5,出现了4次非必要的枚举。
可以看出,这5种方案要在其中选择底数序列的字典序最大的方案,那么该方案必定是非递增排列,根据这个特点,可以剪去大量非必要枚举。
第1个位置枚举范围为: 1 ~ ,当第1个位置选择了a,那么第2个位置的枚举范围为:1 ~ a, 以此类推。
④为选择底数序列的字典序最大的方案,每次枚举从大到小枚举。
ps.库函数pow()使用的注意点:Click here
以下代码:
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
using namespace std;
vector<int> temp,ans;
int N,K,P,maxsum=0;
int power(int x,int p) //自行编写power函数
{
int a=1;
while(p--)
a*=x;
return a;
}
void DFS(int left,int sum) //left表示还剩多少,sum表示当前底数和
{
if(left<=0||temp.size()>=K)
{
if(left==0&&temp.size()==K&&sum>maxsum)
{
ans=temp;
maxsum=sum;
}
return;
}
else
{
int maxn=temp.empty()?pow(left,1.0/P):temp[temp.size()-1];
//确定最大枚举范围
for(int i=maxn;i>=1;i--) //从大到小枚举
{
temp.push_back(i);
DFS(left-power(i,P),sum+i);
temp.pop_back();
}
}
}
int main()
{
scanf("%d %d %d",&N,&K,&P);
DFS(N,0);
if(ans.empty())
printf("Impossible");
else
{
printf("%d = %d^%d",N,ans[0],P);
for(int i=1;i<ans.size();i++)
printf(" + %d^%d",ans[i],P);
}
return 0;
}