Home PAT 1103 Integer Factorization
Post
Cancel

PAT 1103 Integer Factorization

Link

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <cmath>
using namespace std;
int n,k,p,m,maxv;
int power[21];
vector<int>ans,temp;
void DFS(int sum,int index,int cur){
    if(temp.size()==k){
        if(sum==0&&cur>maxv){
            ans=temp;
            maxv=cur;
        }
        return;
    }
    for(int i=index;i>=1;--i){
        if(sum>=power[i]){
            temp.push_back(i);
            DFS(sum-power[i],i,cur+i);
            temp.pop_back();
        }
    }
}
int main() {
    scanf("%d%d%d",&n,&k,&p);
    m=20;
    for(int i=1;i<=20;++i){
        power[i]=pow(i,p);
        if(power[i]>n){
            m=i-1;
            break;
        }
    }
    DFS(n,m,0);
    if(ans.size()==0) printf("Impossible\n");
    else{
        printf("%d = ",n);
        for(int i=0;i<k;++i){
            if(i!=0) printf(" + ");
            printf("%d^%d",ans[i],p);
        }
        printf("\n");
    }
    return 0;
}
This post is licensed under CC BY 4.0 by the author.