题意:输入五个范围在-50~50的系数,求一个五元三次方程有多少组解,解的范围也是-50~50。
做法:遍历方程的前两项,将值存到hash表中,再遍历后三项,看得到的值的相反数是否在hash表中。
我用map hash,效率较低。
#include <iostream>
#include <map>
using namespace std;
typedef map < int, int > M_TYPE;
const int n = 50;
int cal(int x)
{
return x * x * x;
}
int main()
{
int c[5], i, j, k, key, ans = 0;
M_TYPE mymap;
M_TYPE::iterator it;
for (i = 0; i < 5; i++)
cin >> c[i];
for (i = -1 * n; i <= n; i++){
if (i == 0) continue;
for (j = -1 * n; j <= n; j++){
if (j == 0) continue;
key = c[0] * cal(i) + c[1] * cal(j);
it = mymap.find(key);
if (it == mymap.end())
mymap.insert(make_pair(key, 1));
else it->second++;
}
}
for (i = -1 * n; i <= n; i++){
if (i == 0) continue;
for (j = -1 * n; j <= n; j++){
if (j == 0) continue;
for (k = -1 * n; k <= n; k++){
if (k == 0) continue;
key = - c[2] * cal(i) - c[3] * cal(j) - c[4] * cal(k);
it = mymap.find(key);
if (it != mymap.end())
ans += it->second;
}
}
}
cout << ans << endl;
return 0;
}