CF447A DZY Loves Hash 题解
Content
众所周知,\(\texttt{hash}\) 的基本操作就是将一个值取模之后存储,但这样肯定会起冲突,例如 \(p=10,x_1=11,x_2=21\) 时,\(x_1\equiv x_2\pmod p\),那么 \(x_1,x_2\) 就起冲突。现在给定 \(p,n\) 及 \(n\) 个正整数 \(x_1,x_2,x_3,...,x_n\),找出最先起冲突的位置。
数据范围:\(2\leqslant p,n\leqslant 300,0\leqslant x_i\leqslant 10^9\)。
Solution
这道题目很明显会想到桶的思想,就是开个桶把所有的 \(x_i\mod p\) 都存进去,然后边判断有没有重复的就行。
或许你会说,\(x_i\leqslant 10^9\),数组太大了啊。
但是我们看到:\(p\leqslant 300\)。
根据取模的定义,也就是说,\(0\leqslant x_i\mod p<300\),不算大的。所以开数组是可以过这道题目的,而且这题的范围不大,所以很轻松就可以过去。
Code
#include <cstdio>
#include <bitset>
using namespace std;
int n, p, hashh[307];
int main() {
scanf("%d%d", &p, &n);
for(int i = 1; i <= n; ++i) {
int x;
scanf("%d", &x);
if(hashh[x % p]) return printf("%d", i), 0;
hashh[x % p] = 1;
}
return printf("-1"), 0;
}