E. Nearly Shortest Repeating Substring
time limit per test: 2 seconds
memory limit per test: 256 megabytes
input: standard input
output: standard output
Input
The first line contains a single integer t t t ( 1 ≤ t ≤ 1 0 3 1 \leq t \leq 10^3 1≤t≤103) — the number of test cases.
The first line of each test case contains a single integer n n n ( 1 ≤ n ≤ 2 ⋅ 1 0 5 1 \leq n \leq 2\cdot10^5 1≤n≤2⋅105) — the length of string s s s.
The second line of each test case contains the string s s s, consisting of lowercase Latin characters.
The sum of n n n over all test cases does not exceed 2 ⋅ 1 0 5 2\cdot10^5 2⋅105.
Output
For each test case, print the length of the shortest string k k k satisfying the constraints in the statement.
Example
inputCopy
5
4
abaa
4
abba
13
slavicgslavic
8
hshahaha
20
stormflamestornflame
outputCopy
1
4
13
2
10
Note
In the first test case, you can select k = a k = \texttt{a} k=a and k + k + k + k = aaaa k+k+k+k = \texttt{aaaa} k+k+k+k=aaaa, which only differs from s s s in the second position.
In the second test case, you cannot select k k k of length one or two. We can have k = abba k = \texttt{abba} k=abba, which is equal to s s s.
AC代码:
#include<map>
#include<set>
#include<stack>
#include<cmath>
#include<queue>
#include<string>
#include<bitset>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<numeric>
//#define endl '\n'
using namespace std;
typedef long long ll;
typedef pair<int, int>PII;
const int N=3e5+10;
const int MOD=998244353;
const int INF=0X3F3F3F3F;
const int dx[]={-1,1,0,0,-1,-1,+1,+1};
const int dy[]={0,0,-1,1,-1,+1,-1,+1};
const int M = 1e8 + 10;
int t, n, v[N];
string a, b;
bool check(int x)
{
int cnt1 = 0, cnt2 = 0;
for(int i = x; i < n; i ++)
{
if(a[i % x] != a[i]) cnt1 ++;
if(b[i % x] != b[i]) cnt2 ++;
}
if(cnt1 <= 1 || cnt2 <= 1) return true;
return false;
}
int main()
{
cin >> t;
while(t --){
memset(v, 0, sizeof v);
cin >> n;
cin >> a;
b = a;
reverse(a.begin(), a.end());
int cnt = 0;
for(int i = 1; i <= n; i ++)
{
if(n % i == 0)
{
if(check(i))
v[++ cnt] = i; //v[++ cnt] = n / i;
}
}
sort(v + 1, v + 1 + cnt);
if(v[1] != 0) cout << v[1] << endl;
else cout << n << endl;
}
return 0;
}