跳到正文

算法·理论

Hash Trick

JustRaincaot约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年8月22日
收录
2025年12月12日
更新
2026年10月31日
篇幅
约 3 分钟
题目
P3121

版本

  1. v1当前

众所周知本题需要一个比它的弱化版复杂度更低的 hash。

我们可以充分发扬人类智慧,用一个 vector 存下来每个模式串的最后一个字母,查询时直接用 vector 做匹配,然后无伤通过本题。

于是我们得到了只有 3636 行且可以媲美 AC 自动机的代码

仅仅比使用 AC 自动机的代码慢了大约 50ms50ms。

比目前唯一一篇使用 Hash 题解(463ms463ms)快了将近 250ms250ms。

(建议没有写过 P4824 的先把 P4824 写了)

Code - 199ms199ms:

C++
#include <bits/stdc++.h>
#define int unsigned long long
using namespace std;
constexpr int prm=131,maxn = 1e5+5;
int n,pwr[maxn],hb,h[maxn],al,blmax,sl,hs,l;
string a,str;
vector< pair<int,int> > tr[26];
char stk[maxn];
signed main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	cin>>a>>n;
	for(int i=1;i<=n;i++){
		cin>>str;
		str = ' ' + str;
		hs = 0,l = str.length()-1;
		for(int j=1;j<=l;j++)hs = hs*prm+str[j];//处理前缀和哈希
		tr[str[l]-'a'].push_back({hs,l});//放到vector里面
		blmax = max(blmax,l);
	}
	pwr[0] = 1;
	for(int i=1;i<=blmax;i++)pwr[i] = pwr[i-1] * prm;
	a = ' '+a;al = a.length()-1;
	h[0] = 0;
	for(int i=1;i<=al;i++){
		stk[++sl] = a[i];
		h[sl] = h[sl-1]*prm + a[i];
		for(auto pii:tr[a[i]-'a']){//直接与vector里的hash值相比较
			if(sl>=pii.second && pii.first==h[sl]-h[sl-pii.second]*pwr[pii.second]){
				sl-=pii.second;
				break;
			}
		}
	}
	for(int i=1;i<=sl;i++)cout<<stk[i];
	return 0;
}
原文
存档评论2 条抓取于