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.
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】背包问题 | 从N个整数中选择K个数
但是一波三折啊——先是连测试样例都没通过,检查到原来是pow函数有误差,就自己写了个,没问题了。提交,然后又一大堆的段错误和超时,好半天才发现是sqrt函数的问题,sqrt和pow的参数都是double类型,直接用来和整型比较好像会有问题。超时是因为频繁调用自己写的pow函数。最后没辙还是参考了书上的代码。
不要在递归中频繁调用函数,这道题n的数据很小,可以在dfs前提前打表记录到数组中。以及可以让index递减来遍历,这样可以保证字典序大的序列优先被选中,避免比较造成的时间浪费。
#include<cstdio>
#include<vector>
using namespace std;
int n,k,s,maxSum = 0;
vector<int> squ,tmp,out;
int powFx(int x)
{
int sum = 1,i;
for(i=0;i<s;i++)
sum *= x;
return sum;
}
//从0开始不要从1,因为这样数组下标才能一一对应平方和
void squIni()
{
int x = 0,i = 0;
while(x<=n)
{
squ.push_back(x);
x = powFx(++i);
}
}
void dfs(int index,int sum,int sumSqu,int nowK)
{
//如果满足条件
if(sumSqu==n&&nowK==k)
{
//更新和最大值以及最优序列
if(sum>maxSum)
{
maxSum = sum;
out = tmp;
}
return;
}
//中断条件 index最小为1
if(sumSqu>n||nowK>k||index<1) return;
//选择index
tmp.push_back(index);
//index而不是index-1,因为可以重复
dfs(index,sum+index,sumSqu+squ[index],nowK+1);
//不选择index
tmp.pop_back();
dfs(index-1,sum,sumSqu,nowK);
}
int main()
{
int i;
scanf("%d%d%d",&n,&k,&s);
squIni();
//从squ里的最后一个数字开始寻找
dfs(squ.size()-1,0,0,0);
//如果没有这样的序列
if(out.size()==0)
{
printf("Impossible");
return 0;
}
printf("%d = ",n);
for(i=0;i<out.size();i++)
{
printf("%d^%d",out[i],s);
if(i!=out.size()-1)
printf(" + ");
}
return 0;
}
本文探讨了 K-P 分解算法,这是一种将正整数 N 表达为 K 个正整数 P 次方之和的方法。文章详细介绍了算法的输入输出规范,提供了示例,并分享了解题过程中的挑战及解决方案。
734

被折叠的 条评论
为什么被折叠?



