POJ1840 Eqr (哈希)

题目点我点我点我

题目大意:给出一个5元3次方程,输入其5个系数,求它的解的个数。

思路:直观去暴力肯定会超时。换个思路,-(a1*x1^3+a2*x1^3)=(a3*x3^3+a4*x4^3+a5*x^3)。先用hash数组记录左边式子相同值的次数,这里要注意的是a1=a2时,x1=m、x2=n和x1=n、x2=m值相同,但是是两个解,然后暴力枚举右边式子。
另外,hash数组的上界就取决于a1 a2 x1 x2的组合,四个量的极端值均为50,因此上界为 50*50^3+50*50^3=12500000,由于sum也可能为负数,因此我们对hash[]的上界进行扩展,扩展到25000000,当sum<0时,我们令sum+=25000000存储到hash[]。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
using namespace std;
short hashn[25000001];
int main()
{
    int a1,a2,a3,a4,a5;
    while(cin>>a1>>a2>>a3>>a4>>a5)
    {
        memset(hashn,0,sizeof(hashn));
        for(int x1=-50;x1<=50;x1++)
        {
            if(x1==0)continue;
            for(int x2=-50;x2<=50;x2++)
            {
                if(x2==0)continue;
                int sum=(a1*x1*x1*x1+a2*x2*x2*x2)*(-1);
                if(sum<0)
                    sum+=25000000;
                hashn[sum]++;
            }
        }
        int ans=0;
        for(int x3=-50;x3<=50;x3++)
        {
            if(x3==0)continue;
            for(int x4=-50;x4<=50;x4++)
            {
                if(x4==0)continue;
                for(int x5=-50;x5<=50;x5++)
                    {
                        if(x5==0)continue;
                        int sum=(a3*x3*x3*x3+a4*x4*x4*x4+a5*x5*x5*x5);
                        if(sum<0)
                            sum+=25000000;
                        if(hashn[sum])
                            ans+=hashn[sum];
                    }
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

你可能感兴趣的:(POJ1840 Eqr (哈希))