PAT1103.Integer Factorization
题目
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,⋯,a**K } is said to be larger than { b1,b2,⋯,b**K } if there exists 1≤L≤K such that a**i=b**i for i<L and a**L>b**L.
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
代码
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> factor;
vector<int> ans;
vector<int> tmp;
int N,K,P,fsum;
int pow(int t,int pow)
{
int a=1;
for(int i=0;i<pow;i++)
a*=t;
return a;
}
void DFS(int index,int nowK,int factSum,int powSum)
{
//stop
if(powSum>N) return;
if(nowK==K)
{
if(powSum==N&&factSum>fsum)
{
fsum=factSum;
ans=tmp;
}
return;
}
if(index>=1)
{
//select factor[index]
tmp.push_back(index);
DFS(index,nowK+1,factSum+index,powSum+factor[index]);
tmp.pop_back();
//not select factor[index]
DFS(index-1,nowK,factSum,powSum);
}
}
int main()
{
scanf("%d%d%d",&N,&K,&P);
int i,t;
for(i=0;(t=pow(i,P))<=N;i++)
{
factor.push_back(t);
}
i--;
DFS(i,0,0,0);
if(fsum>0)
{
printf("%d = %d^%d",N,ans[0],P);
for(i=1;i<K;i++)
printf(" + %d^%d",ans[i],P);
}
else
printf("Impossible\n");
return 0;
}
分析
主要思路是DFS。
- 预处理先计算出不大于N的所有$i^p$用于后续搜索
- cmath中的pow函数返回值为double,在转换成int的时候是直接截断,例如10^2=100,在某些编译器下会出现(int)pow(10,2) => 99 ,所以只好自己写一个pow
- DFS参数:当前搜索index,搜索到第nowK个数,因子和factSum,$i^p$ 之和powSum
- 刚进入DFS的时候nowK是0
- DFS的各种条件挺烦人的,还有vector在codebloks里无法调试,多注意吧