PAT (Advanced Level) Practice 1103 Integer Factorization

傷城~ 2023-07-03 02:42 117阅读 0赞

回溯就可以解,记一个坑,在计算a的n次方时,如果你需要的是整数,最好不要用pow,而是自己写一个。

我的编译器使用pow的时候,如果传的值不是double类型的而是int类型的数值,会产生比较大的误差,如10的2次方可能的出的结果就是99,而非100。

还有,自己写的pows不会超时,而使用pow函数会有个测试点超时。

  1. #include <iostream>
  2. #include <vector>
  3. #include <math.h>
  4. using namespace std;
  5. int n,k,p,m,maxn=-999;
  6. vector<int> temp,result;
  7. int pows(int a,int e){
  8. int sum =1;
  9. while(e!=0){
  10. sum=sum*a;
  11. e--;
  12. }
  13. return sum;
  14. }
  15. void f(int i){
  16. if(k<0) return;
  17. if(k==0&&n==0){
  18. bool larger=false;
  19. int sum=0;
  20. for(int j=0;j<temp.size();j++){
  21. sum+=temp[j];
  22. if(result.size()!=0&&temp[j]>result[j]) larger=true;
  23. }
  24. if(sum>maxn ||(sum==maxn&&larger)){
  25. result=temp;
  26. maxn=sum;
  27. }
  28. return;
  29. }
  30. for(int h=i;h<=m;h++){
  31. int facor=pows(h,p);
  32. if(n-facor>=0){
  33. n-=facor;
  34. k--;
  35. temp.push_back(h);
  36. f(h);
  37. temp.pop_back();
  38. n+=facor;
  39. k++;
  40. }else{
  41. return;
  42. }
  43. }
  44. }
  45. int main()
  46. {
  47. cin>>n>>k>>p;
  48. int tn=n;
  49. for(int i=1;i<=n;i++){
  50. if(pows(i,p)>=n){
  51. m=i;//阈值
  52. break;
  53. }
  54. }
  55. f(1);
  56. if(result.size()==0){
  57. cout<<"Impossible"<<endl;
  58. }else{
  59. cout<<tn<<" = ";
  60. for(int i=result.size()-1;i>=0;i--){
  61. cout<<result[i]<<"^"<<p;
  62. if(i!=0){
  63. cout<<" + ";
  64. }
  65. }
  66. }
  67. return 0;
  68. }

发表评论

表情:
评论列表 (有 0 条评论,117人围观)

还没有评论,来说两句吧...

相关阅读