习题如下:
其中核心段落在于void Lagrange(int n)函数,其中有针对a)的简化版,更容易理解,如有需要可与我联系
#include "Stack.h"
struct Po {
int base;
Po(int i = 1) :base(i) {}
friend int operator+(int a, Po b);
friend int operator*(int a, Po b);
};
int operator+(int a, Po b)
{return a + std::pow(b.base, 2);}
int operator*(int a, Po b)
{ return a * std::pow(b.base, 2); }
ostream& operator<<(ostream& out, Stack<Po>& stk)
{
out << "{ ";
for (int i = 0; i < stk.size(); ++i) {
out << stk[i].base;
i == stk.size()-1 ? out << " " : out << ", ";
}
out << "}" << "^2";
return out;
}
int sum(Stack<Po>& stk) {
int sum = 0;
for (int i = 0; i < stk.size(); ++i) { sum = sum + stk[i]; }
return sum;
}
void backTrack(Po& p, Stack<Po>& stk) {
stk.pop();
p.base = ++(stk.top()).base;
}
void Langrange(int n) {
Po p(0);
Stack<Po> stk;
for (int i = 0; i < 4; ++i) { stk.push(p); }
std::vector<Stack<Po>> pv;
int _sum;
while ( (_sum = sum(stk)) != n && (4 * stk[0]) <= n) {
if (_sum < n) {
if (stk.size() < 4) { stk.push(p); }
else { ++stk.top().base; }
}
else {backTrack(p, stk);}
if (sum(stk) == n) {
if (stk.size() != 4) {backTrack(p, stk);}
else { pv.push_back(stk); backTrack(p, stk);}
}
}
cout << "n: " << n << " ";
for (std::vector<Stack<Po>>::iterator it = pv.begin(); it != pv.end(); ++it)
{ cout << *it<<" "; }
cout << endl;
}
|