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;
}
相关推荐
zmzb01033 分钟前
C++课后习题训练记录Day55
开发语言·c++
李白同学6 分钟前
C++:继承
开发语言·c++
k***92166 分钟前
【C++】STL详解(九)—priority_queue的使用与模拟实现
开发语言·c++
Hard but lovely39 分钟前
C++11: 自定义异常&&标准异常体系&&回顾c异常处理方式
开发语言·c++
jianfeng_zhu1 小时前
整数数组匹配
数据结构·c++·算法
Chrikk1 小时前
现代化 C++ 工程构建:CMake 与包管理器的依赖治理
开发语言·c++
ozyzo1 小时前
例题
c++
smj2302_796826522 小时前
解决leetcode第3782题交替删除操作后最后剩下的整数
python·算法·leetcode
世转神风-2 小时前
qt-kits-警告:No C++ compiler,无法正常解析工程项目.pro文件
开发语言·c++
王老师青少年编程3 小时前
csp信奥赛C++标准模板库STL(12):C++ STL 中的 next_permutation详解
c++·stl·排列·标准模板库·csp·信奥赛·permutation