http://acm.nyist.net/JudgeOnline/problem.php?pid=136
枚举x1 和 x2 ,得到一个值,然后枚举 x3 , x4, x 5 ,得到另外一个值,两个值相等,找到所有的不同的x。
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<map>
using namespace std;
const int p = 19373;
const int a = 2* 50*50*50*50;
typedef struct Node
{
int value,num;
struct Node * next;
}node;
node * res[p];//结构体指针数组
int main()
{
int T,x1,x2,x3,x4,x5,a1,a2,a3,a4,a5;
int i ,j,k;
//node* res[p];
for(i = 0; i < p; i++)
res[i] = new node;//创建哈希点
while(cin>>T)
{
while(T--)
{
int t ,x;
for(i = 0; i< p; i++)//哈希点初始化
{
res[i]->next = NULL;
res[i]->num = 0;
}
cin>>a1>>a2>>a3>>a4>>a5;
for(i = -50;i <= 50 ; i++)//枚举x1,x2
{
if(i == 0)continue;//注意 所有的x 不能为0
for(j = -50; j <= 50; j++)
{
if(j == 0) continue;
x = a1*i*i*i + a2*j*j*j;
int sum = x >= 0?x:-x;//取模要用绝对值
sum %= p;
node* p1;//这个地方注意不要开成节点了,下面会让它指向哈希点下一个位置,指针就行了,不然会超内存
node* p2 = new node;//
p1 = res[sum]->next;
int flag = 0;
while(p1)//沿着哈希点找,如果找到就标记flag = 1,找不到就把这个数插进去
{
if(p1->value == x)
{
flag = 1;
p1->num++;
delete p2;
break;
}
p1 = p1->next;
}
if(!flag)//没有找到,用p2 保存这个数的信息,插入到哈希表中
{
p2->value = x;
p2->num= 1;
p2->next = res[sum]->next;
res[sum]->next = p2;
}
}
}
long long ans =0;
for(i = -50; i <= 50; i++)
{
if(i == 0) continue;
for(j = -50; j <= 50; j++)
{
if(j == 0) continue;
for(k = -50; k <= 50; k++)
{
if(k == 0) continue;
x = a3*i*i*i + a4*j*j*j + a5*k*k*k;
int sum = x >0? x:-x;
if(sum > a) continue;//优化的地方,如果大于 a 就不用找了
sum %= p;
node* p1 = res[sum]->next;
while(p1)
{
if(p1->value == -x)
{
ans += p1->num;
break;
}
else
p1 = p1->next;
}
}
}
}
cout<<ans<<endl;
}
}
return 0;
}