【PAT甲级】1103 Integer Factorization (30分)

1103 Integer Factorization (30分)

The KP 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 KP 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 12²+4²+2²+2²+1², or 11²+6²+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 { a1,a2,⋯,aK } is said to be larger than { b1,b2,⋯,bK } if there exists 1≤LK 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次方之和,因子以非增顺序排列。多个解中取因子之和最大的,若和相同则取因子的字典序在前的。没解输出Impossible

  • 设置数组a:将index=0开始的数字的P次方存到数组a中,直到a[index]>n。

  • 全局变量:设置数组tempAns和ans,变量facSum和maxFacSum

    数组tempAns存放当前解的临时因子们,ans存放最优解的因子们。

    maxFacSum最优解的因子之和,初值设置为-1。

  • 开始dfs:

    • tempK表示当前K的个数,当tempKK时,判断tempSum当前总和N且(是否为最优解)facSum当前解的因子之和>maxFacSum:更新最优结果变量ans和maxFacSum。

    • index从高后前遍历数组a

      • 判断当前项a[index]是否加入解:tempSum+a[index]<=N,满足则更新tempAns,并递归调用dfs确定下一项

      • 判断是否完成一个解:index==1

      • 若不满足tempSum+a[index]<=N,则index--,因子变小再判断。


代码(参考柳神)

#include<iostream>
#include<vector>
#include<cmath>

using namespace std;

int K,N,P;
vector<int> a,tempAns,ans;
int maxFacSum=-1;

/*初始化:计算a数组*/
void init() {
	int temp=0;
	for(int i=1; temp<=N; i++) {//注意;i从1开始
		a.push_back(temp);
		temp=pow(i,P);
	}
}
/*dfs*/
void dfs(int index,int tempK,int tempSum,int facSum) {
	if(tempK==K) {
		if(tempSum==N&&facSum>maxFacSum) {
			ans=tempAns;
			maxFacSum=facSum;
		}
		return;
	}

	while(index>=1) {
		if(tempSum+a[index]<=N) {
			tempAns[tempK]=index;//使用数组访问必须对vector进行resize
			dfs(index,tempK+1,tempSum+a[index],facSum+index);
		}
		if(index==1) return;
		index--;
	}

}
int main() {
	scanf("%d %d %d",&N,&K,&P);

	init();
	tempAns.resize(K);
	dfs(a.size()-1,0,0,0);
	if(maxFacSum==-1) {
		printf("Impossible");
		return 0;
	}

	printf("%d = ",N);
	for(int i=0; i<ans.size(); i++) {
		if(i!=0) printf(" + ");
		printf("%d^%d",ans[i],P);
	}

	return 0;
}

单词

  • factorization:因式分解

    factor:因子

  • If there is a tie , ..:平手(相等)

posted @ 2020-01-27 17:04  musecho  阅读(359)  评论(0编辑  收藏  举报