Codeforces Round 937 (Div. 4)----->E. Nearly Shortest Repeating Substring

一,思路:

1.这题很容易想到枚举n的因数(时间复杂度n^(1/2)),然后根据这个长度枚举字符串,看是否满足最多只有一个不相同(时间复杂度 n)。总的时间复杂度是 ( n根号n )的级别。又n是1e5级别所以可以过。但是当n是1e6就不行了。

2.难点在于如何判断,一个字符串的不同字符数量,主要是 hshahaha这个不好判断。由这个样例启发,我们可以将字符串反转和不反转两种情况求最小不相同字符数量。(只要是相同的反转过来也是相同的)。hshahaha------>ahahahsh。

二,代码:

复制代码
#include <iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<set>
#include<stack>
#include<queue>
#include<map>
using namespace std;

const int N=200;

typedef  long long ll;
typedef pair<int,int> pii;

string str;
int n;

bool check(int x){

    int res=1e9;
//反转和不反转两个数量的最小值
    for(int k=0;k<2;k++) {

        int cnt1=0;

//用双指针来计算不相同的字符数量
        for (int i = 0, j = x; j < n; j++) {
            if (str[j] != str[i]) cnt1++;
            i = (i + 1) % x;
        }

        res=min(res,cnt1);
        reverse(str.begin(), str.end());
    }

    if(res>1) return false;
    else return true;

}

void Solved() {

    cin>>n;
    cin>>str;

    int res=1e9;
//枚举因数
    for(int i=1;i<=n/i;i++){
        if(n%i==0){
           if(check(i)) res=min(res,i);
           if(check(n/i)) res=min(res,n/i);
        }
    }

    cout<<res<<endl;
}

int main()
{
    int t;
    cin>>t;

    while(t--) {
        Solved();
    }
    return 0;
}
相关推荐
优雅的潮叭7 小时前
c++ 学习笔记之 shared_ptr
c++·笔记·学习
多米Domi0117 小时前
0x3f第33天复习 (16;45-18:00)
数据结构·python·算法·leetcode·链表
SunkingYang7 小时前
QT中使用Lambda表达式作为槽函数用法,以及捕获列表和参数列表用法与区别
c++·qt·用法·lambda表达式·捕获列表·槽函数·参数列表
微露清风7 小时前
系统性学习C++-第二十二讲-C++11
java·c++·学习
罗湖老棍子7 小时前
【例4-11】最短网络(agrinet)(信息学奥赛一本通- P1350)
算法·图论·kruskal·prim
方圆工作室8 小时前
【C语言图形学】用*号绘制完美圆的三种算法详解与实现【AI】
c语言·开发语言·算法
Lips6118 小时前
2026.1.16力扣刷题
数据结构·算法·leetcode
代码村新手8 小时前
C++-类和对象(中)
java·开发语言·c++
kylezhao20199 小时前
C# 文件的输入与输出(I/O)详解
java·算法·c#
CodeByV9 小时前
【算法题】堆
算法