PAT A1103 Integer Factorization
线性dfs,注意每次深搜完状态的维护~
#include<bits/stdc++.h> using namespace std; const int maxn=1010; vector<int> v,tmp,path; int n,k,p; void init () { int t=0,cnt=1; while (t<=n) { v.push_back(t); t=pow(cnt,p); cnt++; } } int maxFacSum=-1; void dfs (int nowindex,int nowsum,int nowK,int facSum) { if (nowK>k||nowsum>n) return; if (nowK==k) { if (nowsum==n) { if (facSum>maxFacSum) { path=tmp; maxFacSum=facSum; } } //tmp.pop_back(); return; } while (nowindex>=1) { tmp.push_back(nowindex); dfs (nowindex,nowsum+v[nowindex],nowK+1,facSum+nowindex); tmp.pop_back(); if (nowindex==1) return; nowindex--; } } int main () { scanf ("%d %d %d",&n,&k,&p); init (); dfs (v.size()-1,0,0,0); if (maxFacSum==-1) { printf ("Impossible"); return 0; } printf ("%d = ",n); for (int i=0;i<path.size();i++) { if (i!=0) printf (" + "); printf ("%d^%d",path[i],p); } return 0; }