PAT A1103 Integer Factorization【DFS】

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.

一个正整数N的K-P因数分解是把N分解成K个正整数的P次幂之和。你需要编写一个程序对于任何正整数N,K,P找到N的K-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.

每一个测试样例用一行给出了3个正整数N(≤400),K(≤N)和P(1<P≤7)

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​​+4^​2​​+2^​2​​+2^​2​​+1^​2​​, or 11​^2​​+6​^2​​+2^​2​​+2​^2​​+2​^2​​, 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 { a​1​​,a​2​​,⋯,a​K​​ } is said to be larger than { b​1​​,b​2​​,⋯,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.

对每一个测试样例,如果解决方案存在,按照如图格式输出

n[i]是第i个因数,所有的因数按照非递增顺序输出

注意:解决方案可能不只有一个,比如169的5-2因数分解有9个解决方案,比如12^2+4^2+2^2+2^2+1^2或者11^2+6^2+2^2+2^2+2^2或者其他。你需要输出因数之和最大的那一个。如果有不只一个方案因数之和最大,那么选择最大的因数序列, 如果存在1≤L≤K使得i<L时ai=bi,aL>bL,,那么序列{a1,a2......ak}比{b1,b2.....bk}大

#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;

int n,k,p,maxFacSum=-1;
//fac记录0^p 1^p ...i^p使得i^p为不超过n的最大数
//ans存放最优底数序列   temp存放递归中的临时底数序列 
vector<int> fac,ans,temp;
//power函数计算x^p 
int power(int x){
	int ans=1;
	for(int i=0;i<p;i++){
		ans*=x;
	}
	return ans; 
} 
//init函数预处理fac数组,
void init(){
	int i=0,temp=0;
	while(temp<=n){
		fac.push_back(temp);
		temp=power(++i);
	}
} 

void DFS(int index,int nowK,int sum,int facSum){
	if(sum==n&&nowK==k){
		if(facSum>maxFacSum){
			ans=temp;
			maxFacSum=facSum;
		}
		return;
	}
	if(sum>n||nowK>k) return;
	if(index-1>=0){
		temp.push_back(index);
		DFS(index,nowK+1,sum+fac[index],facSum+index);//选的分支 
		temp.pop_back();
		DFS(index-1,nowK,sum,facSum);//不选的分支 
	}
}

int main(){
	scanf("%d%d%d",&n,&k,&p);
	init();
	DFS(fac.size()-1,0,0,0);//从fac最后一位开始往前搜索
	if(maxFacSum==-1) printf("Impossible\n");
	else{
		printf("%d = %d^%d",n,ans[0],p);
		for(int i=1;i<ans.size();i++){
			printf(" + %d^%d",ans[i],p);
		}
	} 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38179583/article/details/86707410