PAT 1103 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,⋯,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
-
题目大意
给定正整数N, K, P,将N表示未K个正整数的P次方之和(P>1),要求选择底数和最大和底数序列最大的方案 -
代码实现
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int N, K, P;
vector<int> fac, temp, ans;
int power(int x){ //求i的P次方
int temp1 = 1;
for(int i = 0; i < P; i++)
temp1 *= x;
return temp1;
}
void init(){ //对P次方不超过N的数进行初始化
int temp = 0;
int i = 0;
while(temp <= N){
fac.push_back(temp);
//temp = pow(++i, P);
temp = power(++i);
}
}
int maxfac = -1;
//sum 为当前选中数P次方之和
// nowk为当前选中的数的个数
void DFS(int index, int nowk, int sum, int sumfac){
if(nowk == K && sum == N){
if(sumfac > maxfac ){
ans = temp;
maxfac = sumfac;
}
return;
}
if(nowk > K || sum > N) return;
if(index -1 >= 0){
//选中第index个数
temp.push_back(index);
DFS(index, nowk+1, sum + fac[index], sumfac + index);
temp.pop_back();
//未选中第index 个数
DFS(index - 1, nowk, sum, sumfac);
}
}
int main()
{
scanf("%d%d%d", &N, &K, &P);
init();
DFS(fac.size() - 1, 0, 0, 0);
if(ans.empty())
printf("Impossible");
else {
printf("%d = %d^%d", N, ans[0],P);
int size1 = ans.size();
for(int i = 1; i < size1; i++){
printf(" + %d^%d",ans[i],P);
}
}
return 0;
}
标签:index,PAT,temp,int,sum,1103,ans,Integer,include 来源: https://blog.csdn.net/xiao1guaishou/article/details/94653562