栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

C - Canine poetry

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

在第8个点TLE了,,,

TLE代码如下:

#include 

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

using namespace std;

typedef long long LL;
typedef pair 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("%dn", res);
}

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

    return 0;
}

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

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

仿题解代码如下:

#include 
#include 

#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 

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

很不幸,,不是这个因素

第四个因素:

标记数组 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是比较优的选择,,,用的时候多注意就行。

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1008850.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号