C - Canine poetry (关于时间复杂度的细节)

C - Canine poetry

思路:只需判断长度为2,或长度为3的字符串即可。

在第8个点TLE了,,,

TLE代码如下

#include <bits/stdc++.h>

#define fast ios::sync_with_stdio(false), cin.tie(nullptr); cout.tie(nullptr)

using namespace std;

typedef long long LL;
typedef pair<int, int> PII;

const int N = 1e6 + 10;
const int mod = 998244353;

int T;

void solve()
{
    char str[N];
    cin >> str + 1;
    
    int len = strlen(str + 1);
    
    int res = 0;
    bool st[N] = {0};
    for(int i = 2; i <= len; i ++ )
    {
        if(!st[i - 1] && !st[i] && str[i - 1] == str[i]) res ++, st[i] = true;
        if(!st[i - 2] && !st[i] && str[i - 2] == str[i]) res ++, st[i] = true;
    }
    
    printf("%d\n", res);
}

int main()
{
    //fast;
    scanf("%d", &T);
    //scanf("%d", &T);
    while(T -- )
        solve();

    return 0;
}

如果细看,会发现思路正确,时间复杂度为 O(n),貌似没什么毛病。

但是很不幸,TLE了,本来以为要优化成O(logn),即、i += 2,但,本人实力有限,优化过后,WA2,,,然后就去看题解,此代码为仿照题解的代码

仿题解代码如下

#include <iostream>
#include <string>

#define fast ios::sync_with_stdio(false), cin.tie(nullptr); cout.tie(nullptr)

using namespace std;

int T;

int main()
{
    fast;
    cin >> T;
    while(T -- )
    {
        string str;
        cin >> str;
        
        int len = str.size();
        int res = 0;
        
        for(int i = 0; i < len; i ++ )
        {
            if(str[i] == '#') continue;
            if(i + 2 < len  && str[i + 2] == str[i])
                res ++, str[i + 2] = '#';
            if(i + 1 < len  && str[i + 1] == str[i])
                res ++, str[i + 1] = '#';
        }
        
        cout << res << endl;
    }

    return 0;
}

貌似思路相同,时间复杂度都是O(n),,,

于是,开始控制变量法判断是哪个因素使我的代码TLE

判断过程如下

第一个因素:

scanf 与 cin 未解除同步限制,导致 cin 读取速度太慢

加上如下代码解除同步限制,只能cin和cout

ios::sync_with_stdio(false), cin.tie(nullptr); cout.tie(nullptr)

但不是这个因素,,,这就很奇怪,,,

第二个因素:

调用太多次 solve 函数 ? 

于是将 solve() 的代码 写入 while 中,

很不幸仍然失败,,

第三个因素 :

#include <bits/stdc++.h>

头文件过多也会消耗一点点时间

很不幸,,不是这个因素

第四个因素:

标记数组 st[N]

考虑到调用数组的问题。

首先考虑到调用另一个数组st会耗用时间,于是将st数组去除后,成功AC!!!

于是开始考虑st数组为什么会 TLE

直到我看到这样一行代码:

const int N = 1e6 + 10;

题目要求为最多 1e5,这里却声明 1e6 或许就是这里导致TLE,

不出所料,换成 1e5 便成功了,

然后反思 什么地方用到 1e6 ???

 n 最大为 1e5,for循环最大 1e5 根本到不了 1e6,于是目光锁定到这行代码

bool st[N] = {0};
等效于:bool st[1e6] = {0};

数组初始化问题???

参考此文章:C语言数组初始化的三种方法

此文章中详细论述了,

int st[N] = {0} 调用了 memset函数

众所周知,memset是很慢的,这样的例子不止一个,,memset所导致的time limited exceeded

对于memset时间复杂度的详细分析可见下面文章:memset时间复杂度分析

总结上述文章内容,给出结论:

memset的时间复杂度为O(n) 与 for循环初始化类似,慎用慎用慎用!!!

 但貌似memset是比较优的选择,,,用的时候多注意就行。

最后,感谢观看!(可以通过评论区向博主提出建议哦,😊)

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

AC自动寄

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

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

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

打赏作者

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

抵扣说明:

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

余额充值