PAT甲1103. Integer Factorization (30)

由于要比较字典序列,可对因数从大到小遍历,此时先获得有效序列的字典序列必然大于后获得的。

#include <cstdio>
#include <cstdlib>
#include <string.h>
#include <cmath>
#include <algorithm>
#include <string>
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
using namespace std;

int N,K,P,maxsumf=-1,c;
bool found=false;

vector<int> temp,ans,A;

void DFS(int index,int nowK,int sumpow,int sumf)
{
    if( nowK==K && sumpow == N)
    {
        found=true;
        if(sumf>maxsumf)
        {
            ans=temp;
            maxsumf=sumf;
        }

        return;
    }

    if(index==A.size()||nowK>K||sumpow>N)return;
    temp.push_back(A[index]);
    DFS(index,nowK+1,sumpow+pow(A[index]*1.0,P),sumf+A[index]);
    temp.pop_back();
    DFS(index+1,nowK,sumpow,sumf);
}

void initA()
{
    int x=pow(N*1.0,1.0/P)+1;
    while(x>0)
    {
        A.push_back(x);
        x--;
    }
}

int main()  
{   
    scanf("%d%d%d",&N,&K,&P);
    initA();
    DFS(0,0,0,0);

    if(found)
    {
        printf("%d = ",N);
        for(vector<int>::iterator it=ans.begin();it!=ans.end();it++)
        {
            printf("%d^%d",*it,P);
            if(it!=ans.end()-1)
            {
                printf(" + ");
            }
        }
    }
    else
    {
        printf("Impossible");
    }
    printf("\n");
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yhy489275918/article/details/80118301