题意:
给出表达式 a*x1^2+b*x2^2+c*x3^2+d*x4^2=0,以及a,b,c,d四个数字的输入,要求计算对应的使表达式成立的x的解数有多少组。
注意:
a,b,c,d∈[-50,80]
x1,x2,x3,x4∈[-100,100]
我们不难得出,哈希数组的MAX上界 : 50X100X100X2 = 1000000
于是开一个 > 1000000 长度的hash数组
要点:
(1)这题用 hash 的思想很巧妙,先对 x1 和 x2 进行枚举,存在的存进 hash 表中,然后接下来枚举 x3 和 x4,如果恰好和前面的为相反数,那么答案 + 上前面出现的次数.
(2)用枚举 1~100 而负半区域不考虑,节省枚举数,最后答案因为四个数全部都是正的,而实际上都有每个数都有正有负,故答案 * 16
(3)把平方运算结果存下来。
(4)位运算优化 hash 取模
(5)同号的剪枝
#include <stdio.h>
#include <string.h>
const int MAXN = 50*100*100*2 + 5;
int hash_pos[MAXN];
int hash_neg[MAXN];
int pf[101];
int main() {
int a,b,c,d,i,j,cnt,tmp;
for(i=1; i<101; i++)
pf[i] = i*i;
while(scanf("%d%d%d%d",&a,&b,&c,&d)!=EOF) {
if((a>0 && b>0 && c>0 && d>0) || (a<0 && b<0 && c<0 && d<0)) {
printf("0\n");
continue;
}
memset(hash_pos,0,sizeof(hash_pos));
memset(hash_neg,0,sizeof(hash_neg));
cnt = 0;
for(i=1; i<101; i++) {
for(j=1; j<101; j++) {
tmp = a*pf[i] + b*pf[j];
tmp < 0 ? hash_neg[-tmp]++ : hash_pos[tmp]++; // 0赋在pos数组
}
}
for(i=1; i<101; i++) {
for(j=1; j<101; j++) {
tmp = c*pf[i] + d*pf[j];
cnt += (tmp > 0 ? hash_neg[tmp] : hash_pos[-tmp]); // 0取的时候也要从pos数组中取
}
}
printf("%d\n",cnt<<4);
}
return 0;
}