好的,这是一个家庭作业,所以请试着指导我而不给我直接的答案。我正在尝试使用 Ackermann 函数(C++)来建立记忆。当达到 Ackermann(1,2) 时,它并没有达到我的预期。有些东西告诉我,我可能应该尝试建立 amap
而不是 aarray
用于记忆?任何输入表示赞赏。
#include <iostream>
using namespace std;
static int ackerMemoization[1000];
int acker(int m, int n)
{
if (m == 0)
return n + 1;
if (n == 0)
return acker(m - 1, 1);
if (ackerMemoization[m] != 0)
return ackerMemoization[m - 1];
else
{
ackerMemoization[m] = acker(m - 1, acker(m, n - 1));
return ackerMemoization[m];
//return acker(m - 1, acker(m, n - 1));
}
}
int main()
{
for (int i = 0; i < 1000; i++)
{
ackerMemoization[i] = 0;
}
//cout << "Ackermann(3, 20) = " << acker(3, 20) << endl;
//cout << "Ackermann(4, 0) = " << acker(4, 0) << endl;
//cout << "Ackermann(4, 1) = " << acker(4, 1) << endl;
for (int m = 0; m <= 4; ++m)
{
for (int n = 0; n < 20; ++n)
{
cout << "Ackermann(" << m << ", " << n << ") = " << acker(m, n) << "\n";
}
}
cin.get();
return 0;
}
所以下面是我的新方法。但我不知道为什么我不能memoMap.insert(make_pair(m, n), (acker(m - 1, 1)));
在我的acker
函数中使用?
#include <iostream>
#include <map>
using namespace std;
static map<pair<int, int>, int> memoMap;
int acker(int m, int n)
{
if (m == 0)
return n + 1;
if (n == 0)
{
//memoMap.emplace[make_pair(m, n), (acker(m - 1, 1)];
memoMap.insert(make_pair(m, n), (acker(m - 1, 1)));
return acker(m - 1, 1);
}
else
{
return acker(m - 1, acker(m, n - 1));
}
}
int main()
{
//static map<pair<int, int>, int> memoMap;
//cout << "Ackermann(3, 20) = " << acker(3, 20) << endl;
//cout << "Ackermann(4, 0) = " << acker(4, 0) << endl;
//cout << "Ackermann(4, 1) = " << acker(4, 1) << endl;
for (int n = 0; n <= 20; ++n)
{
cout << "Ackermann(" << 0 << ", " << n << ") = " << acker(0, n) << endl;
}
cout << endl;
for (int n = 1; n <= 20; ++n)
{
cout << "Ackermann(" << 1 << ", " << n << ") = " << acker(1, n) << endl;
}
cout << endl;
for (int n = 2; n <= 20; ++n)
{
cout << "Ackermann(" << 2 << ", " << n << ") = " << acker(2, n) << endl;
}
cout << endl;
for (int n = 3; n <= 20; ++n)
{
cout << "Ackermann(" << 3 << ", " << n << ") = " << acker(3, n) << endl;
}
cout << endl;
for (int n = 4; n <= 2; ++n)
{
cout << "Ackermann(" << 4 << ", " << n << ") = " << acker(4, n) << endl;
}
cin.get();
return 0;
}