pat1103
来源:互联网 发布:2016海外代购数据 编辑:程序博客网 时间:2024/06/15 07:34
- Integer Factorization (30)
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 = n1^P + … nK^P
where ni (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 ibL
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,主要考的是你的dfs的方式,还有剪枝;
此处声明:用math库里的pow会超时第五个样例点
我原先错的dfs方式每次因子都从1开始遍历,这样会造成太多的重复情况,像169里有一种情况是6,6,6,6,5但也会遍历5,6 ,6,6,6多次,像下面代码似的总是从小到大,少了太多太多的遍历
#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<stack>#include<cmath>#include<vector>using namespace std;int n,k,p;vector<int>que;vector<int>ppx;int MAX = 0;int Pow(int m,int n){ int sum = 1; for(int i = 1;i <= n;++i) { sum *= m; } return sum;}void dfs(int m){ //printf("%d\n",m); if(m < 0){ return ; } if(que.size() > k){ return ; } if(m != 0 && que.size() == k) return ; if(m == 0 && que.size() == k) { int sum = 0; for(int i = 0;i < k;++i) { sum += que[i]; } if(sum >= MAX){ ppx = que; MAX = sum; } return ; } //这儿的优化总是找的是从小到大的 //后面更新了的虽然和相同,但也比原先的大, //这种方式减少了很多重复情况 int start = (que.size() == 0) ? 1:que[que.size() - 1]; //每次因子都从前一个因子往大走 for(int i = start;i <= (int)sqrt(m);++i) { if(Pow(i,p) <= m) { que.push_back(i); dfs(m - pow(i,p)); que.pop_back(); } }}int main(){ scanf("%d %d %d",&n,&k,&p); dfs(n); if(ppx.size() == 0){ printf("Impossible\n"); return 0; } printf("%d = %d^%d",n,ppx[ppx.size() - 1],p); for(int i = ppx.size() - 2;i >= 0;--i) { printf(" + %d^%d",ppx[i],p); } cout << endl; return 0;}