哈希应用----hdoj1840

/******************************************************
Copyright:
Author:
Date:
Description:
1、哈希应用
2、注意max取值上限为50*50^3*2
3、处理冲突时只需要把sum++改为sum+=hash[ans];
4、学到新的数据类型short,只占两个字节,int会占4个字节
*******************************************************/

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

#define max 12500000
short hash[max<<1];
int main()
{
    int a[5];
    int i;
    int x1,x2,x3,x4,x5;

        int sum = 0;
        int d = 0;
        memset(hash,false,sizeof(hash));
        for(i = 0; i < 5; i++)
            scanf("%d",&a[i]);

        for(x1 = -50; x1 <= 50; x1++)
        {
            if(x1 == 0)
                continue;

            for(x2 = -50; x2 <= 50;x2++)
            {
                if(x2 == 0)
                    continue;
                int ans = (a[0]*x1*x1*x1+a[1]*x2*x2*x2)*(-1);
                if(ans < 0)
                    ans += max<<1;
                hash[ans]++;
            }
        }

        for(x3 = -50; x3 <= 50; x3++)
        {
            if(x3 == 0)
                continue;
            for(x4 = -50; x4 <= 50; x4++)
            {
                if(x4 == 0)
                    continue;
                for(x5 = -50; x5 <= 50; x5++)
                {
                    if(x5 == 0)
                        continue;
                    int ans = (a[2]*x3*x3*x3 + a[3]*x4*x4*x4 + a[4]*x5*x5*x5);
                    if(ans < 0)
                        ans += max<<1;

                    sum += hash[ans];
                }
            }
        }
        printf("%d\n",sum);
}

你可能感兴趣的:(C++,哈希)