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 = n[1]^P + ... n[K]^P的格式。如果无法拆成指定格式,那么则输出Impossible。若n可以拆成多个不相同的序列,输出序列和最少的序列,若序列和相同则输出非递增的一个序列,例如:可以拆成两个序列{ 1,2,3,4,5 }、{ 5,4,3,2,1 }
选第二个序列。
解题思路:使用dfs枚举每一位(从第一个数字到第k个数字),枚举到第k个数字时,算一下前k个数字的p次方和是否为给定数字n。
注意,枚举每一位数字时,从最大的开始枚举,这样保证了序列中的数字是从大到小排列的,这样当出现多个序列时,直接选第一个序列即可。
优化思路:单纯用dfs枚举会有测试点超时。可以这样来优化
1.从sqrt(n)开始找第一个数字,因为p>1所以p最小值是2,这意味着第一个数字最大时(int)sqrt(n)。
2.将算过的p次方保存在数组里,就不用每次计算了
#include<bits/stdc++.h>
using namespace std;
vector<int>res,temp;
int maxSum;
int n,p,k,f;
int store[210];
//自带的sqrt返回类型为double,会出现精度问题,所以手写一个int类型的
int Pow(int n,int p)
{
int sum=n;
for(int i = 1;i<=p-1;i++)
{
sum*=n;
}
return sum;
}
//自带的sqrt返回类型为double,会出现精度问题,所以手写一个int类型的
int Sqrt(int n)
{
int i;
for(i=1;i<=n;i++)
{
if(i*i>=n)
return i;
}
}
//level的值表示当前是第几个数字,R表示前level-1个数字的p次方和
void dfs(int i,int level,int R)
{
if(level>k||R>n)
return ;
if(level==k)
{
int sum=0;
//求一下前k个数字的和
for(int j = 0; j < temp.size(); j++)
{
sum+=temp[j];
}
if(R==n)
{
f=1;
if(sum>maxSum)
{
maxSum=sum;
res=temp;
}
}
return ;
}
for(int j = i; j >= 1; j--)
{
int x;
if(store[j]!=0)
{
x=store[j];
}
else
{
x=Pow(j,p);
store[j]=x;
}
if(R+x<=n)
{
temp.push_back(j);
dfs(j,level+1,R+x);
temp.pop_back();
}
}
}
int main()
{
cin>>n>>k>>p;
if(n==0)
{
cout<<"Impossible"<<endl;
return 0;
}
dfs(Sqrt(n),0,0);
if(!f)
{
cout<<"Impossible"<<endl;
}
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;
}