题目描述
如题,给定N个字符串(第i个字符串长度为Mi,字符串内包含数字、大小写字母,大小写敏感),请求出N个字符串中共有多少个不同的字符串。
友情提醒:如果真的想好好练习哈希的话,请自觉,否则请右转PJ试炼场:)
输入输出格式
输入格式:
第一行包含一个整数N,为字符串的个数。
接下来N行每行包含一个字符串,为所提供的字符串。
输出格式:
输出包含一行,包含一个整数,为不同的字符串个数。
输入输出样例
输入样例#1: 复制
5 abc aaaa abc abcc 12345
输出样例#1: 复制
4
说明
时空限制:1000ms,128M
数据规模:
对于30%的数据:N<=10,Mi≈6,Mmax<=15;
对于70%的数据:N<=1000,Mi≈100,Mmax<=150
对于100%的数据:N<=10000,Mi≈1000,Mmax<=1500
样例说明:
样例中第一个字符串(abc)和第三个字符串(abc)是一样的,所以所提供字符串的集合为{aaaa,abc,abcc,12345},故共计4个不同的字符串。
Tip: 感兴趣的话,你们可以先看一看以下三题:
BZOJ3097:http://www.lydsy.com/JudgeOnline/problem.php?id=3097
BZOJ3098:http://www.lydsy.com/JudgeOnline/problem.php?id=3098
BZOJ3099:http://www.lydsy.com/JudgeOnline/problem.php?id=3099
如果你仔细研究过了(或者至少仔细看过AC人数的话),我想你一定会明白字符串哈希的正确姿势的^_^
我也是才学字符串哈希,大概理解是,对于一个字符串,你可以通过某种方式,来将整个字符串转化为一个数值,然后就用这个数值来代表了这个字符串。但是这种计算方式是有一定要求的, 也就是说 在需要计算的字符串很多的情况下,要不同的字符串计算出来的这个数值尽可能的不同,这样才能保证一一对应。。。。都不知道自己在说什么,Orz
AC代码:
///单哈希
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 10;
typedef long long ll;
typedef unsigned long long ull;
ull harsh[maxn]; ///ull 是自动取模,对2^63
char ch[maxn];
ull gethash(char *s){
ull h = 0;
int len = strlen(s);
for(int i = 0;i < len;i ++){
h = h * 13331 + s[i] - '0'; ///这也就是那个 特殊的计算方式
}
return h;
}
int main()
{
int n; scanf("%d",&n);
for(int i = 0;i < n;i ++){
scanf("%s",ch);
harsh[i] = gethash(ch);
}
sort(harsh,harsh + n);
int m = unique(harsh,harsh + n) - harsh;
printf("%d\n",m);
return 0;
}
还有的方法就是多一个计算方式,让两个数值来代表同一个 字符串,这样也就能更加减少 重复的可能。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 10;
typedef long long ll;
typedef unsigned long long ull;
struct xx{
ull a,b; ///ull 是自动取模,对2^63;
}harsh[maxn];
char ch[maxn];
void gethash(char *s,int num){
ull h = 0,h1 = 0;
int len = strlen(s);
for(int i = 0;i < len;i ++){
h = h * 13331 + s[i] - '0'; ///这也就是那个 特殊的计算方式
h1 = h * 9991 + (int) s[i];
}
harsh[num].a = h;
harsh[num].b = h1;
}
bool cmp(xx A,xx B){
if(A.a != B.a)
return A.a < B.a;
return A.b < B.b;
}
int main()
{
int n; scanf("%d",&n);
for(int i = 0;i < n;i ++){
scanf("%s",ch);
gethash(ch,i);
}
int ans = 0;
sort(harsh,harsh + n,cmp);
for(int i = 0;i < n;i ++)
if(harsh[i].a == harsh[i + 1].a && harsh[i].b == harsh[i + 1].b)
ans ++;
printf("%d\n",n - ans);
return 0;
}