搜索专题——DFS A1103 Integer Factorization(30)

 

 

#include <bits/stdc++.h>
#include<math.h>
#include <string>
using namespace std;
//maxFacSum 记录最大底数之和
int n,k,p,maxFaceSum = -1;
vector<int> fac,ans,temp;
int power(int x){
    int ans = 1;
    for(int i = 0;i<p;++i){
        ans *= x;
    }
    return ans;
}
void init(){
    int i = 0,temp = 0;
    while(temp <= n){
        fac.push_back(temp);
        temp = power(++i);
    }
}
void DFS(int index,int nowK,int sum,int facSum){
    if(sum == n && nowK == k){
        if(facSum > maxFaceSum){
            ans = temp;
            maxFaceSum = facSum;
        }
        return;
    }
    if(sum > n || nowK > k){//这种情况下不会产生答案,直接返回
        return;
    }
    if(index - 1 >= 0){
        temp.push_back(index);//把底数index加入临时序列temp
        DFS(index,nowK+1,sum+fac[index],facSum+index);//
        temp.pop_back();
        DFS(index - 1,nowK,sum,facSum);//不选
    }
}
int main(){
    scanf("%d%d%d",&n,&k,&p);
    init();
    DFS(fac.size()-1,0,0,0);
    if(maxFaceSum == -1){
        printf("Impossible\n");
    }else{
        printf("%d = %d^%d",n,ans[0],p);//输出ans的结果
        for(int i=1;i<ans.size();++i){
            printf(" + %d^%d",ans[i],p);
        }
    }
    system("pause");
    return 0;
} 
posted @ 2020-01-19 18:08  JasonPeng1  阅读(123)  评论(0编辑  收藏  举报