当前位置:网站首页>【模板记录】字符串哈希判断回文串
【模板记录】字符串哈希判断回文串
2022-07-17 00:36:00 【你算哪一个bug?】
浙江省赛的第I题Barbecue,用字符串哈希做。
哈希判断回文串:算一个字符串正着过去的哈希值,再算字符串反过来的哈希值。再比较正反字符串的哈希值,相等就说明回文。
贴一下下面的代码,以后碰到相同的题目当作模板来用。(其实写了好几种哈希方法和比较,但是这种相对来说最好理解)
#include <iostream>
#include <string>
using namespace std;
typedef unsigned long long ull;
#define base 2333
const ull N = 1e6 + 5;
ull hash1[N];
ull hash2[N];
ull prev_t[N];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, q;
cin >> n >> q;
string str;
cin >> str;
int len = str.size();
prev_t[0] = 1;
hash1[0] = 0;
hash2[0] = 0;
for (int i = 1; i <= len; i++)//字符串下标为i对应哈希数组的i+1
{
hash1[i] = hash1[i - 1] * base + str[i - 1] - 'a' + 1;
hash2[i] = hash2[i - 1] * base + str[len - i] - 'a' + 1;//反过来的字符串的哈希值
prev_t[i] = prev_t[i - 1] * base;//数组在拿到子串的哈希值时起作用
}
while (q--)
{
int l, r;
cin >> l >> r;
int str_lr = r - l + 1;
if (str_lr % 2 == 0)
{
cout << "Budada\n" ;
}
else if ((hash1[r] - hash1[l - 1] * prev_t[r - l + 1]) ==
hash2[len - l + 1] - hash2[len - r] * prev_t[r - l + 1])//比较一下
{
cout << "Budada\n";
}
else
{
cout << "Putata\n";
}
}
return 0;
}


边栏推荐
- 【PHP】tp6多表连接查询
- ncnn paramdict&modelbin
- [MCU simulation] (XV) instruction system bit operation instructions - bit operation instructions, bit conditional transfer instructions
- Go language realizes sending SMS verification code and logging in
- 【单片机仿真】(十九)介绍汇编、汇编指令、伪指令
- 审视自己投资的路
- 【回归预测】基于粒子滤波实现锂离子电池寿命预测附matlab代码
- PyTorch最佳实践和代码模板
- 5. Is the asynctool framework flawed?
- HCIA's first static routing experiment
猜你喜欢
随机推荐
Nat comprehensive experiment
ResNet学习笔记
[MCU simulation] (XV) instruction system bit operation instructions - bit operation instructions, bit conditional transfer instructions
审视自己投资的路
Elk log analysis system
[redis] what is progressive rehash
这是数学的问题
[regression prediction] lithium ion battery life prediction based on particle filter with matlab code
【单片机仿真】(十九)介绍汇编、汇编指令、伪指令
JDBC连接Mysql数据库
ncnn DataReader&Extractor&blob
Configure VLAN and use OSPF protocol for layer 3 switches
[MCU simulation] (IX) instruction system - add, ADDC, sub, Inc, Dec, Da of arithmetic operation instructions
Learning network foundation
yolov6 学习初篇
OSPF comprehensive experiment
你能用到的Mysql常用命令
Understand JVM garbage collection in one article
【NoSQL】redis主从、哨兵、集群
Detailed explanation of case when usage of SQL





![[NoSQL] redis master-slave, sentinel, cluster](/img/69/37b80398617040984b006d3d7b71b9.png)



![[redis] what is progressive rehash](/img/99/0b2c81e55a70c41de245612996d1a2.png)