Description:
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 12 2 12^2 122 + 4 2 4^2 42 + 2 2 2^2 22 2 2 2^2 22 + 1 2 1^2 12 , or 1 1 2 11^2 112 + 6 2 6^2 62 + 2 2 2^2 22 + 2 2 2^2 22 + 2 2 2^2 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 ,2 ,⋯,bK } if there exists 1≤L≤K such that ai =bi fori<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
AC代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Pnum(int num,int P);
typedef struct
{
int a[410];
int len;
}record;
record temp,ans,res;//temp为记录结构体,ans为答案结构体,res为待选P次方数组结构体
int N,K,P;
int max;//记录答案最大和
void Init(){
int i=0,b=0;
res.len=0;
while(b<=N){
res.a[res.len++]=b;
b=Pnum(++i,P);//赋值
}
}
int isbigger(record temp,record ans)
{
for(int i=0;i<temp.len;i++)
{
if(temp.a[i]==ans.a[i])continue;
else if(temp.a[i]>ans.a[i])return 1;
else return 0;
}//此处需要考虑到三种情况,不能够只写if(temp.a[i]>ans.a[i])return 1; 否则测试点2不能通过
}
int Pnum(int num,int P)
{
int start=1;
while(P){
start*=num;
P--;
}
return start;
}//当函数局部变量名和全局变量名相同 在函数内部使用局部变量
void DFS(int index,int nowK,int Psum,int sum)
{
if(nowK>K||Psum>N)return;
if(nowK==K&&Psum==N)
{
if(sum>max){
ans=temp;
max=sum;//更新最大值
}
else if(sum==max&&isbigger(temp,ans)){
ans=temp;
}//此段else if可以不写,因为Index从大到小进行遍历,相对大的Index较早被写入temp,已经排好序了
}
if(index>=1){
temp.a[temp.len++]=index;//向temp.a中填入index元素
DFS(index,nowK+1,Psum+res.a[index],sum+index);//选index号数,并且可以重复选
temp.len--;//从temp.a中“弹出”index元素
DFS(index-1,nowK,Psum,sum);//不可选Index号数
}
}
int compare(const void*a,const void*b)
{
int *pa=(int*)a;
int *pb=(int*)b;
return (*pb)>(*pa)?1:-1;//按从大到小进行排序
}
int main()
{
scanf("%d %d %d",&N,&K,&P);
temp.len=0;ans.len=0;//初始化
max=-1;//初始化最大值
Init();//初始化结构体c
DFS(res.len-1,0,0,0);//index需要从大到小进行遍历,否则测试点会超时
if(max==-1){
printf("Impossible\n");
return 0;
}//没有找到合适的
qsort(ans.a,ans.len,sizeof(int),compare);//qsort可以不要,自然有序
printf("%d =",N);
for(int i=0;i<ans.len;i++){
printf(" %d^%d",ans.a[i],P);
if(i<ans.len-1)printf(" +");
}
}