1103 integer factorization
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1103 integer factorization相关的知识,希望对你有一定的参考价值。
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; }
以上是关于1103 integer factorization的主要内容,如果未能解决你的问题,请参考以下文章
PAT甲级1103 Integer Factorization (30分)
PAT 1103 Integer Factorization[难]
PAT 1103 Integer Factorization
1103. Integer Factorization (30)搜索+剪枝——PAT (Advanced Level) Practise