其他分享
首页 > 其他分享> > PAT 1103 Integer Factorization

PAT 1103 Integer Factorization

作者:互联网

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​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.
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

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int N, K, P;
vector<int> fac, temp, ans;
int power(int x){          //求i的P次方
    int temp1 = 1;
    for(int i = 0; i < P; i++)
        temp1 *= x;
    return temp1;
}
void init(){             //对P次方不超过N的数进行初始化
   int temp = 0;
   int i = 0;
   while(temp <= N){
    fac.push_back(temp);
    //temp = pow(++i, P);
    temp = power(++i);
   }
}
int  maxfac = -1;
//sum 为当前选中数P次方之和
// nowk为当前选中的数的个数
void DFS(int index, int nowk, int sum, int sumfac){
    if(nowk == K && sum == N){
        if(sumfac > maxfac ){
            ans = temp;
            maxfac = sumfac;
        }
        return;
    }
    if(nowk > K || sum > N) return;
    if(index -1 >= 0){
        //选中第index个数
        temp.push_back(index);
        DFS(index, nowk+1, sum + fac[index], sumfac + index);
        temp.pop_back();
        //未选中第index 个数
        DFS(index - 1, nowk, sum, sumfac);
    }
}
int main()
{
    scanf("%d%d%d", &N, &K, &P);
    init();
    DFS(fac.size() - 1, 0, 0, 0);
    if(ans.empty())
        printf("Impossible");
    else {
        printf("%d = %d^%d", N, ans[0],P);
        int size1 = ans.size();
        for(int i = 1; i < size1; i++){
            printf(" + %d^%d",ans[i],P);
        }
    }
    return 0;
}

标签:index,PAT,temp,int,sum,1103,ans,Integer,include
来源: https://blog.csdn.net/xiao1guaishou/article/details/94653562