hash(哈希算法)

                                                解方程

Time Limit : 6000/3000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)

Total Submission(s) : 60   Accepted Submission(s) : 31

Font: Times New Roman | Verdana | Georgia

Font Size: ← →

Problem Description

给定一方程如下:
a*x12 + b*x22 + c*x32 + d*x42=0

其中:
a, b, c, d在整数区间[-50,50]内取值,并且都不等于0.

求方程在区间[-100,100] 内的非零整数解的个数。

Input

输入包含多组测试数据。
每组数据占一行,包含4个整数a b c d。

Output

请输出每组数据方程解的个数。

Sample Input

1 2 3 -4
1 1 1 1

Sample Output

39088
0
#include<bits/stdc++.h>
using namespace std;
#define maxx 52333
int f[maxx],g[maxx];
int ha(int k)
{
    int t=k%maxx;
    if(t<0)
    {
        t+=maxx;
    }
    while(f[t]!=0&&g[t]!=k)
    {
        t=(t+1)%maxx;
    }
    return t;
}
int main()
{
    int a,b,c,d,n=0,t[105],s,p;
    for(int i=1;i<=100;i++)
    {
        t[i]=i*i;
    }
    while(scanf("%d%d%d%d",&a,&b,&c,&d)==4)
    {
        n=0;
        if(a>0&&b>0&&c>0&&d>0||a<0&&b<0&&c<0&&d<0)
        {
            printf("0\n"); 
            continue;
        }
        memset(f,0,sizeof(f));
        for(int i=1;i<=100;i++)
        {
            for(int j=1;j<=100;j++)
            {
                s=a*t[i]+b*t[j];
                p=ha(s);
                g[p]=s;
                f[p]++;
            }
        }
        for(int i=1;i<=100;i++)
        {
            for(int j=1;j<=100;j++)
            {
                s=-(c*t[i]+d*t[j]);
                p=ha(s);
                n+=f[p];
            }
        }
        printf("%d\n",n*16);
    }
    return 0;
}

哈希的主要思想就是把数存下标里面(好像是这样),以达到快排的效果

猜你喜欢

转载自blog.csdn.net/balalalalalalala/article/details/81143970