跳到正文

题解

题解:SP32961 ADAJOBS - Ada and Jobs

Amidst约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月2日
篇幅
约 4 分钟
获赞
1
题目
SP32961

版本

  1. v1当前

原来 ACAM 还可以离线。

思路

发现在线不好做,考虑对询问离线。

我们考虑以插入时间为字符串编号,先将所有串都插入,建立 AC 自动机。

对于每一个询问,查询第一个能与之匹配的串的编号是否在询问编号之前即可,具体地,在 Trie 上找到该串的路径,对路径上每个节点暴力跳 fail,最后取编号最小的那个。

我们惊喜地发现每次都暴力跳 fail 的最坏复杂度是 O(n2)O(n^2) 的,于是我们考虑跳完 fail 后把点到根之间的编号最小值记录下来(相当于一种记忆化),这样复杂度是 O(n)O(n),可以接受。

难度在于想到离线。

代码

C++
#include <bits/stdc++.h>
//#include <bits/extc++.h>
//#define int long long
#define __BEGIN_MULTITEST__ \
	signed T; \
	scanf("%d",&T); \
	while(T--) \
	{
#define __END_MULTITEST__ }
using namespace std;
//using namespace __gnu_cxx;
//using namespace __gnu_pbds;
const int N=2e6+5,S=26;
struct _ACAM
{
	int cnt=0;
	int tr[N][S];
	int fail[N],c[N];
	int mp[N];
	int _Insert(string st,int k)
	{
		int u=0;
		for(auto i:st)
		{
			if(!tr[u][i-'a'])
			{
				c[++cnt]=1e9;
				tr[u][i-'a']=cnt;
			}
			u=tr[u][i-'a'];
		}
		c[u]=min(c[u],k);
		return u;
	}
	void _Getfail()
	{
		queue<int> q;
		for(int i=0;i<26;i++)
			if(tr[0][i])
				q.push(tr[0][i]);
		while(!q.empty())
		{
			int tmp=q.front();
			q.pop();
			for(int i=0;i<26;i++)
				if(tr[tmp][i])
				{
					fail[tr[tmp][i]]=tr[fail[tmp]][i];
					q.push(tr[tmp][i]);
				}
				else
					tr[tmp][i]=tr[fail[tmp]][i];
		}
		memset(mp,0xff,sizeof mp);
	}
	int _Mp(int x)
	{
		if(!x)
			return mp[x]=1e9;
		if(~mp[x])
			return mp[x];
		return mp[x]=min(c[x],_Mp(fail[x]));
	}
	int _Query(string st)
	{
		int u=0,ret=1e9;
		for(auto i:st)
			ret=min(ret,_Mp(u=tr[u][i-'a']));
//		cout<<ret<<'\n';
		return ret;
	}
}ACAM;
int n;
int op[N];
string st[N];
signed main()
{
	cin.tie(nullptr)->sync_with_stdio(false);
//	__BEGIN_MULTITEST__
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>op[i]>>st[i];
		if(!op[i])
			ACAM._Insert(st[i],i);
	}
	ACAM._Getfail();
	for(int i=1;i<=n;i++)
		if(op[i])
			cout<<(ACAM._Query(st[i])<i?"YES\n":"NO\n");
//	__END_MULTITEST__
	return 0;
}
原文