Hash—哈希算法
Hash其实是一种散列技术,散列技术是指在记录的存储位置和它的关键字之间建立一个确定的对应关系f,使每一个关键字都对应一个存储位置。即:存储位置=f(关键字)。这样,在查找的过程中,只需要通过这个对应关系f 找到给定值key的映射f(key)。只要集合中存在关键字和key相等的记录,则必在存储位置f(key)处。我们把这种对应关系f 称为散列函数或哈希函数。
哈希冲突
在理想的情况下,每一个 关键字,通过哈希函数计算出来的地址都是不一样的。但是在实际情况中,我们常常会碰到两个关键字key1≠key2,但是f(key1) = f(key2), 这种现象称为冲突,并把key1和key2称为这个散列函数的同义词。
常用Hash算法
BKDRHash
public static int bkdrhash(String str) {
final int seed = 131;
int hash = 0;
for (int i = 0; i < str.length(); i++) {
hash = hash * seed + (int)str.charAt(i);
}
return hash & 0x7FFFFFFF;
}
APHash
public static int aphash(String str) {
int hash = 0;
for (int i = 0; i < str.length(); i++) {
if ((i & 1) == 0) {
hash ^= (hash << 7) ^ (str.charAt(i)) ^ (hash >> 3);
} else {
hash ^= ~((hash << 11) ^ (str.charAt(i)) ^ (hash >> 5));
}
}
return hash & 0x7FFFFFFF;
}
JSHash
public static int jshash(String str) {
int hash = 0;
for (int i = 0; i < str.length(); i++) {
hash ^= (hash << 5) + (int)str.charAt(i) + (hash >> 2);
}
return hash & 0x7FFFFFFF;
}
RSHash
public static int rshash(String str) {
int hash = 0;
int a = 63689;
final int b = 378551;
for (int i = 0; i < str.length(); i++) {
hash = hash * a + (int)str.charAt(i);
a *= b;
}
return hash & 0x7FFFFFFF;
}
SDBMHash
public static int sdbmhash(String str) {
int hash = 0;
for (int i = 0; i < str.length(); i++) {
hash = (int)str.charAt(i) + (hash << 6) + (hash << 16) - hash;
}
return hash & 0x7FFFFFFF;
}
例题
Equations
Consider equations having the following form:
ax12+bx22+cx32+dx42=0
a, b, c, d are integers from the interval [-50,50] and any of them cannot be 0.
It is consider a solution a system ( x1,x2,x3,x4 ) that verifies the equation, xi is an integer from [-100,100] and xi != 0, any i ∈{1,2,3,4}.
Determine how many solutions satisfy the given equation.
Input
The input consists of several test cases. Each test case consists of a single line containing the 4 coefficients a, b, c, d, separated by one or more blanks.
End of file.
Output
For each test case, output a single line containing the number of the solutions.
Sample Input
1 2 3 -4
1 1 1 1
Sample Output
39088
0
题意:求满足方程的解的组数。
ac代码
#include <bits/stdc++.h>
using namespace std;
int a,b,c,d;
const int N=4e6+10;
const int n=50*100*100*2;
int Hash[N];
int main()
{
while(~scanf("%d%d%d%d",&a,&b,&c,&d))
{
if(a>0&&b>0&&c>0&&d>0||a<0&&b<0&&c<0&&d<0)
{
cout<<0<<endl;
continue;
}
memset(Hash,0,sizeof Hash);
int sum=0;
for(int x1=1;x1<=100;x1++)
for(int x2=1;x2<=100;x2++) Hash[n+a*x1*x1+b*x2*x2]++; //hash
for(int x3=1;x3<=100;x3++)
for(int x4=1;x4<=100;x4++) sum+=Hash[-(c*x3*x3+d*x4*x4)+n];
cout<<sum*4*4<<endl; //最后结果需要乘16因为符号不同而且两边都有两个未知数
}
}