1103 Integer Factorization
分数 30
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.
找k个数字的p次方和为n
Sample Input 1:
169 5 2 //5个数2次方的和=169
Sample Output 1:
169 = 6^2 + 6^2 + 6^2 + 6^2 + 5^2
Sample Input 2:
169 167 3
Sample Output 2:
Impossible
#include<iostream>
#include<vector>
#include<cmath>
#include<cstdio>
using namespace std;
//fac存放从0的k次方到不超过n的k次方,facsum存放当前底数之和,maxfacsum存放最大底数之和
//sum=次方之和,ans存放结果 最优序列,temp存放当前临时序列的次方和
int n,k,p,maxfacsum=-1;
vector<int> fac,ans,temp;
int power(int x){//power函数计算x^p
int ans=1;
for(int i=0;i<p;i++){//连续乘p次就是p次方
ans *=x;
}
return ans;
}
void init(){//用init函数来处理fac数组
int i=0,temp=0;
while(temp<=n){
//fac.push_back(temp);//注意要把0的k次方也存放进去
//temp=power(++i);//如果是i++,结果不一样,为7的平方++++6的平方
temp=power(i++);//或者
fac.push_back(temp);
}
}
//dfs函数来访问当前所在fac中的位置cur,走过的fac数,sum和,facsum当前底数和
//cur是fac的下标,fac[cur]数的次方的形式
void dfs(int cur,int count,int sum,int facsum){
if(sum==n && count==k){//当前和为n并且走过的数正好为k个为一个满足的数列
if(facsum>maxfacsum){
maxfacsum=facsum;
ans=temp;
}
return;
}
if(sum>n || count>k) return;
if(cur>=1){
temp.push_back(cur);
dfs(cur,count+1,sum+fac[cur],facsum+cur);//选的分支,还是从当前节点开始选取
temp.pop_back();
dfs(cur-1,count,sum,facsum);//不选的分支
}
}
int main(){
int i;
cin>>n>>k>>p;
init();//!!!一定要初始化数组,不然结果都为不可能
dfs(fac.size()-1,0,0,0);//从fac的最后一位开始算起,这样能保证取的底数都是很大的
if(maxfacsum==-1){//最大值不变,说明没有找到满足的序列
cout<<"Impossible"<<endl;
}
else{
printf("%d = %d^%d",n,ans[0],p);//先输出第一项
for(i=1;i<ans.size();i++){
printf(" + %d^%d",ans[i],p);
}
}
cout<<endl;
return 0;
}