哈希字符串入门 P3370洛谷

题目链接
描述
如题,给定N个字符串(第i个字符串长度为Mi,字符串内包含数字、大小写字母,大小写敏感),请求出N个字符串中共有多少个不同的字符串。

输入格式
第一行包含一个整数N,为字符串的个数。

接下来N行每行包含一个字符串,为所提供的字符串。

输出格式
输出包含一行,包含一个整数,为不同的字符串个数。

输入样例
5
abc
aaaa
abc
abcc
12345
输出样例
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人数的话),我想你一定会明白字符串哈希的正确姿势的_
分析:
其实哈希这个地方比较像模拟十进制数的组成,什么意思呢???
比如1314,这个数可以表示为11000+3100+1*10+4对吧,
其实哈希就是这样来模拟的,只不过是将字符转化为整数罢了(在这里的整数时unsight long long 类型的,这个类型的数字会在越界的时候自动对264取模),然后就可以根据哈希之后的数值来判断是否字符串相等了

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <set>
#include <utility>
#include <sstream>
#include <iomanip>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define inf 0x3f3f3f3f
#define rep(i,l,r) for(int i=l;i<=r;i++)
#define lep(i,l,r) for(int i=l;i>=r;i--)
#define ms(arr) memset(arr,0,sizeof(arr))
//priority_queue<int,vector<int> ,greater<int> >q;
const int N = 1e5 + 10;
const int mod = 1e9+7;
ull base=131,ha[N];
char str[N];
map<ull,bool>ma;
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    #endif // ONLINE_JUDGE
    int n,len,ans=0;
    scanf("%d\n",&n);
    ha[0]=1;
    ull t=0;
    for(int i=0;i<n;i++){
        scanf("%s",str);
        len=strlen(str);
        t=1;
        for(int j=0;j<len;j++){
            t=t*base+str[j];
        }
        if(ma[t]==false)
        ans++,ma[t]=true;
    }
    printf("%d\n",ans);
    return 0;
}

发布了229 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/c___c18/article/details/100979180