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) 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 = n1^P + … nK^P
where ni (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 ibL
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模型。难在如何剪枝上,第5个样例超时,反正我是看了网上才知道要存所以可能的pow数。
dfs的模型得出不难,而剪枝等各种和常数的优化则是一个高深的学问。
代码
#include<iostream>
#include<cstdio>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std;
int n,k,p;
vector<int> ans,temp;
int Pow[25];
int cnt;
int getP(int a,int b)
{
int ans=1;
while(b)
{
if(b&1)
ans*=a;
a*=a;
b>>=1;
}
return ans;
}
int maxSum=0;
void dfs(int left,int l,int pos)
{
if(l==0&&left==0)
{
//cout<<"haha"<<endl;
int sum=0;
for(int i=0;i<temp.size();i++)sum+=temp[i];
if(maxSum<sum)
{
ans=temp;
maxSum=sum;
}
return;
}
while(Pow[pos]>left-l+1)pos--;//剪枝
for(;Pow[pos]>=left/l;pos--)//这种剪枝是因为各个的factor的得出都是从大到小的,即下限不会超过平均水平,这个也是一个难点
{
//cout<<pos<<" "<<l<<endl;
temp.push_back(pos);
dfs(left-Pow[pos],l-1,pos);
temp.erase(temp.end()-1);
}
}
int main()
{
cin>>n>>k>>p;
for(cnt=1;getP(cnt,p)<=n-k+1;cnt++)
Pow[cnt]=getP(cnt,p);
cnt--;
dfs(n,k,cnt);
if(maxSum)
{
cout<<n<<" = "<<ans[0]<<"^"<<p;
for(int i=1;i<ans.size();i++)
cout<<" + "<<ans[i]<<"^"<<p;
}
else
cout<<"Impossible";
return 0;
}