您的位置:首页 > 其它

NYOJ 138 找球号(二)(哈希)

2015-10-25 14:39 169 查看
题目:http://acm.nyist.net/JudgeOnline/problem.php?pid=138

题意:两种操作,加数字和询问某些数字有没有被加入。

思路:

因为数字的范围很大,直接用cnt[ i ]表示数字 i 有没有加入会爆内存,而最多加入10^6个数字,所以要用哈希表。让范围1-10^8的数字的10^6个数每个对应一个值,加入时,在哈希值对应的数组中加上这个数;询问时,在哈希值对应的数组里遍历查找。

这题数据比较水。

#include <stdio.h>
#include <string.h>
#define INF 0x7fffffff
#define MOD 1000000007
using namespace std;
typedef long long ll;
const int MAXN = 1000006;
int cnt, key[MAXN], head[MAXN], nex[MAXN];

int gethash(int x)
{
return x % 93425; //- -随机选的一个数
}

void add(int x)
{
int k = gethash(x);
key[cnt] = x;
nex[cnt] = head[k]; //在哈希值对应数组中加入x,方法同用数组建树
head[k] = cnt++;
}

int find(int x)
{
int k = gethash(x);
for(int t = head[k]; t != -1; t = nex[t])
{ //遍历哈希值k对应的数组
if(key[t] == x) return 1;
}
return 0;
}

int main()
{
#ifdef LOCAL
freopen("data.in", "r", stdin);
#endif

int n, m, x;
char op[10];
while(scanf("%d", &n) != EOF)
{
memset(key, 0, sizeof(key));
memset(head, -1, sizeof(head));
memset(nex, 0, sizeof(nex));
cnt = 0;
for(int i = 0; i < n; i++)
{
scanf(" %s%d", op, &m);
for(int j = 0; j < m; j++)
{
scanf("%d", &x);
if(op[0] == 'A')
{
add(x);
}
else
{
if(find(x))
printf("YES\n");
else printf("NO\n");
}
}
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: