cf 984 D. I Love 1543

D. I Love 1543

思路

模拟,判断循环字符串中"1534"的个数,由于"1534"中每个字符都不相同,所以直接判断\(s+s[1...3]\)中有多少个"1534"就行了。

对于判断任意的子串的个数,只需要开始判断一次原串的子串个数,然后逐一计算把原串第一位字符移动到末尾的贡献值就行了(m-1次),复杂度是\(O(n*m+m*m)\)

代码

//来自kotatsugame
#include<iostream>
#include<cassert>
using namespace std;
int N,M;
string S[1000];
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int T;cin>>T;
	for(;T--;)
	{
		cin>>N>>M;
		for(int i=0;i<N;i++)cin>>S[i];
		int cnt=0;
		for(int r=0;r<min(N,M)/2;r++)
		{
			string now="";
			for(int y=r;y<M-r-1;y++)now+=S[r][y];
			for(int x=r;x<N-r-1;x++)now+=S[x][M-r-1];
			for(int y=M-r-1;y>r;y--)now+=S[N-r-1][y];
			for(int x=N-r-1;x>r;x--)now+=S[x][r];
			assert(now.size()>=4);
			now+=now.substr(0,3); //这里就是这样处理的
			for(int i=0;i+4<=now.size();i++)
			{
				if(now[i]=='1'&&now[i+1]=='5'&&now[i+2]=='4'&&now[i+3]=='3')cnt++;
			}
		}
		cout<<cnt<<"\n";
	}
}

posted @ 2024-11-04 10:46  MGNisme  阅读(30)  评论(0)    收藏  举报