您的位置:首页 > 其它

POJ 1840--Eqs

2014-07-28 14:40 225 查看
此题要求所有满足方程的整数非零解,若直接枚举是10^10。
很容易想到Hash,以空间换时间,将方程进行简要变换:a1x13+ a2x23
= -1*(a3x33+ a4x43+
a5x53)。

首先枚举左边方程的所有可能结果,以相乘之后和的值作为Hash的key映射到slot中,slot中存的数据为此结果的个数(不同的x1和x2可能有相同的结果)。
然后枚举方程右边的解,若在hash表中找到相同的值则结果加加。复杂度为O(10^6)。

对称优化:

首先为了节省乘法资源(FPGA的习惯,C里面作用不大),左右两边方程进行枚举时,变量都不需要直接枚举[-50,50]的空间,有3/4的立方运算都是多余的,如x1 = 5,x2 = 6;x1 = -5,x2 = 6;x1 = -5,x2 = -6,x1 = 5,x2 = -6的乘法我们都可以只计算5^3,6^3,再进过变换得来。所以每个变量枚举时只需要枚举[1,50]的区间,再经过变换得到其它三个值。
然后其实上面的变换有一半也是多余的,即是我们只需要计算(5,6)以及(5,-6),但要对上述方程左右两边取绝对值,方程的解得个数为由此计算结果的两倍。

证明:设X = (x1,x2),Y = (x3,x4,x5),若(X,Y)为原方程的解,则(X,Y)(X,-Y)(-X,Y)(-X,-Y)都为绝对值方程的解,且绝对值方程的解只能由原方程的解变换而来,所以绝对值方程的解是原方程解得两倍。但是通过程序计算的解中完全没有包含X,Y的相反数,也即是只包含了上面四个解中的一个,所以程序计算的解的个数是原方程解的个数的二分之一。

#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
#define maxN 139919
#define cube(x)   (x*x*x)
#define base 12500000
#define maxM 25000000

struct node
{
int sum;
short num;
node* next;
}* hashTab[maxN];

int hashInsert(int tmpSum)
{
tmpSum = abs(tmpSum);
int slot = tmpSum%maxN;
node* tmpNode;
for(tmpNode = hashTab[slot];tmpNode != NULL;tmpNode = tmpNode->next)
{
if(tmpNode->sum == tmpSum)
{
tmpNode->num++;
return 0;
}
}
tmpNode = new node;
tmpNode->sum = tmpSum;
tmpNode->num = 1;                  //初始化为0错误
tmpNode->next = hashTab[slot];
hashTab[slot] = tmpNode;
return 0;
}

short hashCheck(int tmpSum)
{
tmpSum = abs(tmpSum);
if(tmpSum <= base)
{
int slot = tmpSum%maxN;
node* tmpNode;
for(tmpNode = hashTab[slot];tmpNode != NULL;tmpNode = tmpNode->next)
{
if(tmpNode->sum == tmpSum)
return tmpNode->num;
}
}
return 0;
}

int main()
{
short i,j,k;
int tmpSum,resultNum;
int tmpProduct[3];
short a[5];
resultNum = 0;
memset(hashTab,0,sizeof(hashTab));
for(i = 0;i < 5;i++)
scanf("%hd",a+i);
for(i = 1;i <= 50;i++)
for(j = 1;j <= 50;j++)
{
tmpProduct[0] = a[0]*cube(i);
tmpProduct[1] = a[1]*cube(j);
tmpSum = tmpProduct[0]+tmpProduct[1];
hashInsert(tmpSum);
tmpSum = tmpProduct[0]-tmpProduct[1];
hashInsert(tmpSum);
}
for(i = 1;i <= 50;i++)
for(j = 1;j <= 50;j++)
for(k = 1;k <= 50;k++)
{
tmpProduct[0] = a[2]*cube(i);
tmpProduct[1] = a[3]*cube(j);
tmpProduct[2] = a[4]*cube(k);
tmpSum = tmpProduct[0]+tmpProduct[1]+tmpProduct[2];
resultNum += hashCheck(tmpSum);
tmpSum = tmpProduct[0]+tmpProduct[1]-tmpProduct[2];
resultNum += hashCheck(tmpSum);
tmpSum = tmpProduct[0]-tmpProduct[1]-tmpProduct[2];
resultNum += hashCheck(tmpSum);
tmpSum = tmpProduct[0]-tmpProduct[1]+tmpProduct[2];
resultNum += hashCheck(tmpSum);
}
printf("%d\n",resultNum*2);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: