dfs+prune
AC代码:
#include <vector> #include <cstdio> #include <algorithm> #include <cmath> #include <numeric> using namespace std; class sol{ public: vector<int> seq; int sum; }; bool operator<(const sol& a,const sol& b){ if(a.sum != b.sum) return a.sum > b.sum; else{ for(int i = 0;i < a.seq.size();i++){ if(a.seq[i] < b.seq[i]) return false; else if(a.seq[i] > b.seq[i]) return true; } } } void rec(vector<int>& pvec,vector<sol>& ret,sol seq,int n,int k,int p,int id){ if(n < k || k == 0 && n != 0 || n > k * pvec[id]) return; else if(n == 0 && k == 0){ seq.sum = accumulate(seq.seq.begin(),seq.seq.end(),0); ret.push_back(seq); } else{ int root(pvec.size() - 1); for(int i = id;i >= 1;i--){ int tmp(pvec[i]); if(n >= tmp + k - 1){ seq.seq.push_back(i); rec(pvec,ret,seq,n - tmp,k-1,p,i); seq.seq.pop_back(); } } } } int main(){ int n,k,p; scanf("%d %d %d",&n,&k,&p); vector<sol> ret; sol seq; vector<int> pvec; int num(0); while(true){ int tmp(pow(float(num),p)); if(tmp <= n){ pvec.push_back(tmp); } else{ break; } num++; } int id(pvec.size() - 1); rec(pvec,ret,seq,n,k,p,id); if(ret.size() == 0) printf("Impossible\n"); else{ sort(ret.begin(),ret.end()); printf("%d = ",n); for(int i = 0;i < k;i++){ if(i == 0){ printf("%d^%d",ret[0].seq[0],p); } else{ printf(" + %d^%d",ret[0].seq[i],p); } } printf("\n"); } return 0; }
时间: 2024-10-10 07:52:08