a1x13+ a2x23+ a3x33+ a4x43+ a5x53=0
所有数的范围[-50,50]
给出 a1, a2, a3, a4, a5的值,x1, x2, x3, x4, x5为变量,求这个方程有多少组解。
可以先三重循环枚举x1,x2,x3计算前面三项的值sum1, count[sum1]++;
然后二重循环枚举x4,x5计算后面二项的值sum2, answer += count[-sum2];
这里要注意,sum1, sum2的值可以为负数,所以要加上一个合适的值,同时也要考虑count[]数组的大小。
当然也可以用STL_map 代替count[]数组就简单多了。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 18800000;
short hash[2*maxn];
int main() {
int a[10];
for(int i=1; i<=5; ++i)
scanf("%d", &a[i]);
for(int x1=-50; x1<=50; ++x1) {
if(x1==0) continue;
for(int x2=-50; x2<=50; ++x2) {
if(x2==0) continue;
for(int x3=-50; x3<=50; ++x3) {
if(x3==0) continue;
int tmp = x1*x1*x1*a[1] + x2*x2*x2*a[2] + x3*x3*x3*a[3];
hash[tmp + maxn]++;
}
}
}
int ans = 0;
for(int x4=-50; x4<=50; ++x4) {
if(x4==0) continue;
for(int x5=-50; x5<=50; ++x5) {
if(x5==0) continue;
int tmp = x4*x4*x4*a[4] + x5*x5*x5*a[5];
ans += hash[maxn-tmp];
}
}
printf("%d\n", ans);
return 0;
}