90pts wa#3 求调
查看原帖
90pts wa#3 求调
791903
elonzhang楼主2025/1/20 18:21

rt,trie树写法。

#include <bits/stdc++.h>
using namespace std;
#define freop(s) freopen(s".in","r",stdin);freopen(s".out","w",stdout);
#define int long long
#define double long double
#define re register
#define endl '\n'
#define inf 0x7f7f7f7f7f7f7f7f
#define lowbit(x) (x&-x)
#define pii pair<int,int>
#define fir first
#define sec second
#define umap unordered_map
#define uset unordered_set
const int N=4e5+1,M=30;
int n,m,sz,tot;
string s;
struct node{
	int cnt,siz,ch[M];
}trie[N];

inline void ins(){
	int u=0,p;
	for(int i = 0;i<sz;++i){
		p=s[i]-'a';
		if(!trie[u].ch[p]) trie[u].ch[p]=++tot;
		u=trie[u].ch[p],++trie[u].siz;
	}
	++trie[u].cnt;
}

inline int q1(int u,int st){//匹配半段查询距离为0的部分
	int p;
	for(int i = st;i<sz;++i){
		p=s[i]-'a';
		if(!trie[u].ch[p]) return 0;
		u=trie[u].ch[p];
	}
	return trie[u].cnt;
}
int dfs(int u,int pos){
	int p=s[pos]-'a',sum=0;
	if(!(pos^sz)){
		for(int i = 0;i<26;++i) if(trie[u].ch[i]) sum+=trie[trie[u].ch[i]].cnt;
		return sum;
	}
	if(!(pos^(sz-1))) sum+=trie[u].cnt;
	for(int i = 0;i<26;++i){
		if(!trie[u].ch[i]) continue;
		if(i^p&&i==s[pos+1]-'a') sum+=q1(trie[u].ch[i],pos+2); //操作1
		if(i^p&&trie[trie[u].ch[i]].ch[p]) sum+=q1(trie[u].ch[i],pos);//操作2
		if(i^p&&trie[trie[u].ch[i]].ch[s[pos+1]-'a']) sum+=q1(trie[u].ch[i],pos+1);//操作3
		if(!(i^p)) sum+=dfs(trie[u].ch[p],pos+1);//无事发生
	}
	return sum;
}

signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
//	freop();
//↑以上为初始化↑
//------------------------------
	cin >> n >> m;
	for(int i = 1;i<=n;++i) cin >> s,sz=s.size(),ins();
	for(int i = 1;i<=m;++i){
		cin >> s,sz=s.size();
		int t=q1(0,0);
		if(t) cout << -1 << endl;
		else cout << (dfs(0,0)) << endl;
	}
	return 0;
}
2025/1/20 18:21
加载中...