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
思路:
void DFS(int index,int nowk,int sum,int facSum){}
当前处理的fac几号位,记为index.已经选了几个数,记为nowk,记录当前选出的数底数和为sum,当前选出的数底数和facSum开一个vector< int >fac,存放所有不超过N的n^p,为了对应把0也存放进去。vector< int>ans存放最优底数序列,vector< int>temp存放当前选中的底数序列
- 注意输出格式,=前有空格,然后” + “有两个空格。
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
int n,k,p,i,maxFacSum=-1;//最大底数和
vector<int> fac,ans,temp;
//fac记录最优底数序列,temp存放递归中的临时底数序列。fac记录0^p,1^p,````i^p
int power(int x)//算x^n
{
int ans=1;
for ( i=0;i<p;i++)
ans=ans*x;
return ans;
}
void init()//写fac
{
int j=0;
int temp=0;
while(temp<=n){
fac.push_back(temp);
temp=power(++j);
}
}
void DFS(int index,int nowk,int sum,int facSum)
{
//当前访问fac[index],nowk 选中个数,sum选中数的和,facSum选中底数和
if(sum==n&&nowk==k)
{
if(facSum>maxFacSum)
{
ans=temp;
maxFacSum=facSum;
}
return;
}
if(sum>n||nowk>k)return;
if(index-1>=0)
{ //fac[0]不需要选择
temp.push_back(index);
DFS(index,nowk+1,sum+fac[index],facSum+index);
temp.pop_back();
DFS(index-1,nowk,sum,facSum);
}
}
int main()
{
scanf("%d%d%d",&n,&k,&p) ;
init();
DFS(fac.size()-1,0,0,0);
if(maxFacSum==-1)printf("Impossible\n");
else{
printf("%d = %d^%d",n,ans[0],p);
for(i=1;i<ans.size();i++)
{
printf(" + %d^%d",ans[i],p);
}
printf("\n");
}
return 0;
}