给定n个长度为m的字符串,q次询问:第x和第y个是否循环同构

题目

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
string s, t;
int nxt[maxn];
bool mp[1005][1005];
string str[maxn];
void get_next(string s){
  int n = s.size() - 1;
	nxt[1] = 0;
	int idx = 0, i = 2;
	while(i <= n){
		if(s[i] == s[idx + 1]){
			idx++;
			nxt[i] = idx;
			i++;
		}
		else{
			if(idx == 0){
				nxt[i] = 0;
				i++;
			}
			else idx = nxt[idx];
		}
	}
}
int kmp(string s, string t){
	int n = s.size() - 1, m = t.size() - 1;
	int i = 1, j = 1;
	while(i <= n && j <= m){
		if(s[i] == t[j]){
			i++;
			j++;
		}
		else{
			if(j == 1) i++;
			else j = nxt[j - 1] + 1;
		}
	}
	if(j > m) return i - j + 1;
	return 0;
}
void solve(){
	int n, m, i, j;
	cin >> n >> m;
	if(n * n <= 100000){//根号分治,字符串个数较少时,任意两个都让其中一个字符串复制一次,然后kmp跑一遍,用数组记录这两个是否匹配
		for(i = 1; i <= n; i++){//复杂度:O(n*n*m)
      for(j = 1; j <= n; j++){
				if(i == j) mp[i][j] = 1;
				else mp[i][j] = 0;
			} 
			cin >> str[i];
			//cout << str[i] << '\n';
		}
		for(i = 1; i < n; i++){
			t = str[i];
			t = " " + t;//求nxt数组和kmp都要右移一次,因为下标从1开始
			get_next(t);
			for(j = i + 1; j <= n; j++){
				s = str[j];
				s += s;
				s = ' ' + s;
				if(kmp(s, t)) mp[i][j] = mp[j][i] = 1;
 			}
		}
		int q;
		cin >> q;
		while(q--){
			int x, y;
			cin >> x >> y;
			if(mp[x][y] == 1) cout << "Yes\n";
			else cout << "No\n";
		}
	}
	else{//字符串个数较多,长度较短时,对于每一个询问,直接让其中一个字符串复制一次,然后kmp跑一遍。
	     //复杂度O(q*m))
		for(i = 1; i <= n; i++){
			cin >> str[i];
		}
		int q;
		cin >> q;
		while(q--){
			int x, y;
			cin >> x >> y;
			s = ' ' + str[x] + str[x], t = ' ' + str[y];
			get_next(t);
			if(kmp(s, t)) cout << "Yes\n";
			else cout << "No\n";
		}
	}
}
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	int T;
	cin >> T;
	while(T--){
		solve();
	}
	return 0;
}

法二:字符串的最小表示法

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

__night_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值