题目描述
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.
翻译:一个正整数N的K−P因式分解是将N改写为K个正整数的P次方的和。你需要写一个程序对于任何正整数N,K,P,找到N的K−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.
翻译:每个输入文件包含一组测试数据,包含一行3个正整数N(≤400), K (≤N) 和 P (1<P≤7)。一行内的所有数字之间用空格隔开。
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=bifor i<L and aL>bL.
If there is no solution, simple output Impossible.
翻译:对于每组测试数据,如果结果存在,按照以下格式输出:
N = n[1]P + … n[K]P
n[i] (i = 1, …, K) 表示第i个元素。所有元素必须按照降序排输出。
注意:结果可能不为一。例如,169的5-2因式分解有9个结果,例如122+42+22+22+12, 或112+62+22+22+22等。你需要输出元素之和最大的那个。如果还是相同,则选择最大的因数序列–如果有1≤L≤K , 当i<L时 ai=bi,并且 aL>bL则称数列{ a1,a2,⋯,aK}比数列 { b1,b2,⋯,bK} 大。
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+剪枝即可解决。 第一次提交时第2个测试点和第5个测试点错误(从0开始),第5个测试点错误一般是没剪枝或在dfs中循环计算pow()。用一个数组保存一下pow值即可。第2个测试点是自己想当然了,认为从小到大枚举则枚举出的第一个结果一定是和最大的,所以死活过不去,以后要引以为戒。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<vector>
#include<algorithm>
#define INF 99999999
#define bug puts("Hello\n")
using namespace std;
int N,K,P;
int v[410],ans[410];
int power[410];
int ccount=1,flag=0;//ccount用于计算最大的平方值,flag用于判断是否有解
int tmpAns=0;
int countsum(){
int tmp=0;
for(int i=1;i<=K;i++)tmp+=v[i];
return tmp;
}
void reserve(){
if(!flag)flag=1;
int tmpflag=0;
if(countsum()>tmpAns)tmpflag=1,tmpAns=countsum();
if(countsum()==tmpAns){
for(int i=K;i>=1;i--){
if(ans[i]<v[i]){
tmpflag=1;
break;
}
}
}
if(tmpflag)for(int i=1;i<=K;i++)ans[i]=v[i];
}
void print(){
if(!flag)printf("Impossible\n");
else{
printf("%d = ",N);
for(int i=1;i<K;i++){
printf("%d^%d + ",ans[i],P);
}
printf("%d^%d\n",ans[K],P);
}
}
int fun(int k,int sum,int maxcount){
int tmpsum;
int i;
for(i=1;i<=maxcount;i++){
tmpsum=sum+power[i];
if(tmpsum>N)break;
if(tmpsum==N){
if(k==K){v[k]=i;reserve();}
else break;
}
if(k!=K){
v[k]=i;
fun(k+1,sum+power[i],i);
}
}
return 0;
}
int main(){
scanf("%d%d%d",&N,&K,&P);
while(pow(ccount,P)<=N){
power[ccount]=pow(ccount,P);
ccount++;
}
ccount--;
fun(1,0,ccount);
print();
return 0;
}