洛谷P3370 【模板】字符串哈希(c嘎嘎)

[复制链接]
发表于 2024-12-23 00:48:11 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
题目链接:P3370 【模板】字符串哈希 - 洛谷 | 计算机科学教诲新生态
题目难度:普及



解题思路:利用哈希算法,将每一个字符串映射到一个值域较小、可以方便比较的数,然后将哈希值存入到set(不能有重复元素),最后输出set的大小。

代码部分:
  1. #include<bits/stdc++.h>//万能头文件
  2. using namespace std;
  3. typedef unsigned long long ULL;
  4. const int N = 100010,P = 131;
  5. int n;
  6. ULL h[N];
  7. char s[N];
  8. set<ULL>st;
  9. int get_hash(char s[])//哈希函数
  10. {
  11.         h[0] = 0;
  12.         int len = strlen(s);
  13.         for(int i=0; i<len; i++)
  14.         {
  15.                 h[i + 1] = h[i] * P + s[i];
  16.         }
  17.         return h[len];
  18. }
  19. int main()
  20. {
  21.     ios::sync_with_stdio(0);
  22.     cin.tie(0), cout.tie(0);
  23.    
  24.     cin >> n;
  25.    
  26.         while(n--)//读入
  27.         {
  28.                 cin >> s;
  29.                 st.insert(get_hash(s));//插入set中
  30.         }
  31.     cout<<st.size();
  32.              
  33.     return 0;  
  34. }
复制代码

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表