题解:P11034 【MX-X3-T1】「RiOI-4」What beats RiOI

· · 题解

:::align{center}

P11034 题解

题目传送门

1. 题目大意

输入两个字符串 s ,t 。检查 s , t 转小写后是否包含rioi字串:

2. 代码实现

::::success[AC 代码(C++)]{open}

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

string s, t;

bool is_shan(string str) { // 判断字符串是不是“闪”的
    for (char& ch : str) {
        ch = tolower(ch);
    } // 转小写

    if (str.find("rioi") != string::npos) { // 判断是否有rioi子串
        return true;
    }

    return false;
}

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

    if (is_shan(s)) {
        if (is_shan(t)) { // s 和 t 满足
            cout << "Either is ok!";
        } else { // 仅 s 满足
            cout << s << " for sure!"; 
        }
    } else { 
        if (is_shan(t)) { // 仅 t 满足
            cout << t << " for sure!";
        } else { // 没有字符串满足
            cout << "Try again!";
        }
    }

    return 0;
}

::::

3. 这就完了……吗?

我们可以简化一下代码,用一个变量answer存储所有的可能, answer 为 2 * is_shan(s) + is_shan(t) : | s的情况(true 或 false) | t的情况 (true 或 false) | answer | |:-:|:-:|:-:| | false | false | 0 | | false | true | 1 | | true | false | 2 | | true | true | 3 |

这样的话,我们的answer和 s , t 一一对应了!

::::success[AC 代码 Pro(C++)]{open}

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

string s, t;

bool is_shan(string str) { // 判断字符串是不是“闪”的
    for (char& ch : str) {
        ch = tolower(ch);
    } // 转小写

    if (str.find("rioi") != string::npos) { // 判断是否有rioi子串
        return true;
    }

    return false;
}

int main() {
    cin >> s >> t;
    int answer = 2 * is_shan(s) + is_shan(t);

    switch (answer) {
        case 0: cout << "Try again!"; break; // 没有一个满足
        case 1: cout << t << " for sure!"; break; // t 满足
        case 2: cout << s << " for sure!"; break; // s 满足
        case 3: cout << "Either is ok!"; break; // t, s 都满足
    }

    return 0;
}

::::

::::success[AC 代码 Pro(Python)]{open}

str1, str2 = input(), input()
answer = (str1.lower().count("rioi") != 0) * 2 +(str2.lower().count("rioi") != 0)

match answer: # Python 3.10+ 的模式匹配match,相当于switch
    case 0:
        print("Try again!")
    case 1:
        print(f"{str2} for sure!")
    case 2:
        print(f"{str1} for sure!")
    case 3:
        print("Either is ok!")

# 以下是不用match的版本 ↓

"""
if answer == 0:
      print("Try again!")
elif answer == 1:
      print(f"{str2} for sure!")
elif answer == 2:
      print(f"{str1} for sure!")
elif answer == 3:
      print("Either is ok!")
"""

::::

4. 最短写法

::::success[AC 代码压行版(Python)]{open}

str1, str2 = input(), input(); print(["Try again!", f"{str2} for sure!", f"{str1} for sure!", "Either is ok!"][(str1.lower().count("rioi") != 0) * 2 +(str2.lower().count("rioi") != 0)])

::::

5. Q & A

这里会处理大家可能遇到的问题。