1103. Integer Factorization

这里写图片描述

题目的大体意思就是,给出N,k,p三个数字
找出满足N=n_1^P+…n_k^P的所有n的值,并且在所有方法中找到n_1+…+n_k最大的值,如果大小相同,就选择字典序最大的一组数组。
这道题肯定是要通过搜索去寻找最合适的组合,明显是dfs(有点贪心的意思在里面)
首先,先将index^p

#include<iostream>
#include<cstdio>
#include<vector>
#include<cmath>
using namespace std;

vector<int> tmpAns,Ans,data;
int n,k,p,maxfac=-1;
int myindex=1;


void init()
{
    int tmp=0;
    while(tmp<=n)
    {
        data.push_back(tmp);
        tmp=pow(myindex,p);
        myindex++;
    }
}


void dfs(int index,int tmpNum,int tmpK,int fac)
{
    if(tmpNum==n && tmpK==k)
    {
        if(fac>maxfac)
        {
            Ans=tmpAns;
            maxfac=fac;
        }
        return;
    }
    if(tmpNum>n || tmpK>k) return;
    if(index>0)
    {
        tmpAns.push_back(index);
        dfs(index,tmpNum+data[index],tmpK+1,fac+index);
        tmpAns.pop_back();
        dfs(index-1,tmpNum,tmpK,fac);
    }
}

int  main()
{
    scanf("%d %d %d",&n,&k,&p);
    init();
    dfs(data.size()-1,0,0,0);
    if(maxfac==-1) printf("Impossible\n");
    else
    {
        printf("%d = ",n);
        for(int i=0;i<Ans.size();++i)
        {
            if(i==0) printf("%d^%d",Ans[i],p);
            else printf(" + %d^%d",Ans[i],p);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/github_33873969/article/details/80214058
今日推荐