PAT_A1103
错误代码:
#include <iostream> #include <cstdio> #include <cmath> #include <stack> using namespace std; const int maxn = 15; int a[maxn]; int N,K,P,summax = 0; string strmax="0"; void reverse(string& str){ stack<char> tmp; string::iterator it = str.begin(); while(str.size()){ tmp.push(*str.begin()); str.erase(str.begin()); } while(!tmp.empty()){ str += tmp.top(); tmp.pop(); } } void DFS(int index, int nowk, int sumN, int sum, string str){ printf("111"); if(nowk == K ){ printf("333"); if(sumN == N){ printf("333"); reverse(str); if(sum > summax){ summax = sum; strmax.replace(0, strmax.size(), str); } else if(sum == summax && str > strmax){ strmax.replace(0, strmax.size(), str); } } return; } if(sumN > N) return; //选index DFS(index, nowk + 1, sumN + pow(index, P), sum + index, str + (char)index); //不选index DFS(index + 1, nowk, sumN, sum, str); } int main(void) { freopen("in.txt","r",stdin); scanf("%d%d%d",&N,&K,&P); string str; DFS(0, 0, 0, 0, str); if(strmax.size() != 0) printf("%s\n",strmax.c_str()); else printf("Impossible"); fclose(stdin); return 0; }
AC代码:
#include <iostream> #include <cstdio> #include <vector> #include <cmath> using namespace std; int N,K,P; vector<int> vi, tmp, ans; int summax = -1, sumN = 0; void DFS(int index, int nowk, int sum, int sumN){ if(sumN == N && nowk == K){ //终止条件 if(sum > summax){ summax =sum; //更新 ans = tmp; } return ; } if(sumN > N || nowk > K) return; if(index <= 0) return; if(index > 0){ tmp.push_back(index); DFS(index, nowk + 1, sum + index, sumN + vi[index]); tmp.pop_back(); DFS(index - 1, nowk, sum, sumN); } } int main(void){ freopen("in.txt","r",stdin); scanf("%d%d%d",&N,&K,&P); for(int i = 0; pow(i,P) <= N; i++) vi.push_back(pow(i,P)); DFS(vi.size() - 1, 0, 0, 0); if(summax == -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); } } } fclose(stdin); return 0; }