您的位置:首页 > 理论基础 > 数据结构算法

[数据结构]hash小题HD1496(hash开放寻址)

2015-09-29 20:03 330 查看
/*
Name:HDOJ1496 (暴力 hash开放寻址)

Actor:HT

Time:2015年9月29日

Error Reporte:	1.后面俩循环从1开始...题意
2.hash时候注意处理负号!
3.最后别忘了乘16

*/

#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <vector>

#define N 50017
//左边40000种组合可能....而且是素数

using namespace std;

int ihash
;
int val
;

//题目:http://acm.hdu.edu.cn/showproblem.php?pid=1496
//本题用hash的优点是节省空间。时间换空间

int a, b, c, d, sum;

int x2[10010];	//亮点:为减少多次计算平方时间,直接一个表弄出来

int f(int x)
{
int i, j;
int t = x%N;
if (t < 0) t += N;
for (i = 0;; i++)
{
if (ihash[t] == 0 || val[t] == x)
{
return t;
}
t = (t + 1) % N;
}
}

int main()
{
int t, i, j, k;
int temp,n;
for (i = 0; i <= 10002; i++)
x2[i] = i*i;
while (scanf("%d %d %d %d", &a, &b, &c, &d) != EOF)
{
if ((a > 0 && b > 0 && c > 0 && d > 0) ||		//关键剪枝  同号则无解
(a < 0 && b < 0 && c < 0 && d < 0))
{
printf("0\n");
continue;
}
memset(ihash, 0, sizeof(ihash));
memset(val, 0, sizeof(val));
for (i = 1; i <= 100; i++)
{
for (j = 1; j <= 100; j++)
{
temp = a*x2[i] + b*x2[j];
t = f(temp);
ihash[t]++;		//加一次
val[t] = temp;	//赋值
}
}//左等式填hash表
sum = 0;
for (i = 1; i <= 100; i++)
{
for (j = 1; j <= 100; j++)
{
temp = -(c*x2[i] + d*x2[j]);
t = f(temp);
sum += ihash[t];
}
}
printf("%d\n", sum*16);		//由于每一个数可+可- 所以2^4
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: