洛谷B3703 [语言月赛202301] 样例过不去


#include <bits/stdc++.h>
using namespace std;
string s,x;
int n,l,r;
int main(){
    cin>>s>>n;
    for(int i=1;i<=n;i++){
        cin>>l>>r;
        int sx=-1;
        bool aa=true;    
        for(int j=l-1;j<r;j++)
        {
            sx++;
            x[sx]=s[j];    
//            cout<<s[j]<<x[sx]<<sx;
            if(s[j]!='a') aa=false;
        }
        if(aa==true) 
        {
            cout<<"NULL"<<endl<<"Happy Chinese New Year!"<<endl;
            continue;
        }
        for(int j=sx;j>=0;j--)
        {
            if(x[j]=='a') x[j]='z';
            else {
                x[j]--;
                break;
            }
        }
        for(int j=0;j<=sx;j++) cout<<x[j];
        cout<<endl;
        if(s.find(x)!=string::npos) cout<<"Happy New Year!"<<endl;
        else cout<<"Happy Chinese New Year!"<<endl;
    }
}

把题目贴出来看下。

img

我搜索出来只有一个涂色的,和你的这个也不一样啊

你可以看看题解:

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这篇博客: 洛谷B2134 质数的和与积(素数条件)中的 输出格式 部分也许能够解决你的问题。
  • 以下回答由chatgpt基于相关博客总结生成:

    首先,我们可以看到这段代码存在一些潜在的问题和可以优化的空间。

    1. 字符串x没有初始化,直接赋值可能会导致 undefined behavior。
    2. 代码中使用了多次字符串拼接操作,这会导致字符串的重新分配和拷贝,效率较低。
    3. 使用 find 函数查找是否存在字符串 x,时间复杂度较高。

    下面是优化后的代码:

    #include <bits/stdc++.h>
    using namespace std;
    
    int main(){
        string s, x;
        int n;
        cin >> s >> n;
    
        for (int i = 1; i <= n; i++){
            int l, r;
            cin >> l >> r;
            x = s.substr(l - 1, r - l + 1);
    
            if (x == string(x.size(), 'a')){
                cout << "NULL" << endl << "Happy Chinese New Year!" << endl;
            }
            else{
                bool hasHappyNewYear = false;
                for (int j = x.size() - 1; j >= 0; j--){
                    if (x[j] == 'a') {
                        x[j] = 'z';
                    }
                    else{
                        x[j]--;
                        hasHappyNewYear = true;
                        break;
                    }
                }
                cout << x << endl;
    
                if (hasHappyNewYear){
                    if (s.find(x) != string::npos){
                        cout << "Happy New Year!" << endl;
                    }
                    else{
                        cout << "Happy Chinese New Year!" << endl;
                    }
                }
                else{
                    cout << "NULL" << endl << "Happy Chinese New Year!" << endl;
                }
            }
        }
        return 0;
    }
    

    优化方案: - 使用 substr 函数代替 for 循环来生成子串 x,避免了多次复制和拼接操作,提高了效率。 - 添加标志位 hasHappyNewYear,减少了对字符串 x 是否为全 a 的判断次数。 - 在第二个条件判断前添加一个判断,如果 x 不含有 'a',则直接输出结果,并且跳过第二个条件的判断。

    希望以上优化代码和解释能够帮助到你!如果有其他问题需要解答,请随时提问。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^