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+回溯
代码:
#include <iostream>
#include <sstream>
#include <string>
#include <cstdio>
#include <queue>
#include <cstring>
#include <map>
#include <cstdlib>
#include <stack>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define rep(i,a,n) for(int i=a;i<n;i++)
#define mem(a,n) memset(a,n,sizeof(a))
#define DBGS() cout<<"START\n"
#define DBGE() cout<<"END\n"
const int N = 80+5;
const ll INF = 0x3f3f3f3f;
const double eps=1e-4;
int n,k,p;
int maxFacSum=-1;
vector<int>fac,ans,tmpAns;
int myPow(int n) {
int ans=1;
for(int i=0; i<p; i++) {
ans*=n;
}
return ans;
}
void init() {
int ttmp=0,index=1;
while(ttmp<=n) {
fac.push_back(ttmp);
// printf("%d ",ttmp);
ttmp=myPow(index);
index++;
}
}
/***
index:因数分解数组fac的下标
tmpSum:分解序列和
tmpK:因子分解序列的个数
facSum:因子底数之和
*/
void dfs(int index,int tmpSum,int tmpK,int facSum) {
if(tmpSum>n||tmpK>k)
return;
if(tmpK==k) {
if(tmpSum==n&&facSum>maxFacSum) {
ans=tmpAns;
maxFacSum=facSum;
}
return ;//剪枝
}
if(index>=1) {
tmpAns.push_back(index);///选择
dfs(index,tmpSum+fac[index],tmpK+1,facSum+index);
tmpAns.pop_back();///不选
dfs(index-1,tmpSum,tmpK,facSum);
}
}
int main() {
scanf("%d%d%d",&n,&k,&p);
init();
tmpAns.reserve(k);
dfs(fac.size()-1,0,0,0);
// printf("%d %d %d\n",fac.size(),ans.size(),maxFacSum);
if(maxFacSum==-1) {
printf("Impossible");
return 0;
}
printf("%d = ",n);
for(int i=0; i<ans.size(); i++) {
if(i)
printf(" + ");
printf("%d^%d",ans[i],p);
}
return 0;
}