1 条题解

  • 0
    @ 2025-4-7 19:56:27

    该代码用于根据特定规则对输入的由字母数字组成的病毒代码字符串进行变异处理,解题思路如下:

    1. 读取数据:通过循环不断读取输入,当遇到“ENDOFINPUT”时停止。每次读取数据集的起始行获取病毒代码长度n,再读取病毒代码字符串s和结束行。
    2. 递归处理字符串:调用searching函数从字符串第一个字符(位置0)开始处理。
      • 若当前字符为0或已处理到字符串末尾(pos == n),返回0,表示当前片段稳定无变异。
      • 若当前字符为字母(A-Z),递归处理其右侧片段得到变异次数x,根据x的值将当前字母变异为相应数字,并返回1 + x(包含自身变异次数)。
      • 若当前字符为1-9的数字,若右侧存在第n个字符(pos + (s[pos] - '0') < n),递归处理从第n个字符开始的右侧片段得到变异次数x,将当前数字减1,返回1 + x;否则递归处理紧邻右侧片段,同样将当前数字减1并返回1 + x
    3. 输出结果:处理完整个字符串后,输出变异后的字符串。
    #include <iostream>
    #include <string>
    using namespace std;
    int n;
    string s;
    
    // 递归函数,对字符串进行处理
    int searching(int pos) {
        if (s[pos] == '0' || pos == n) {
            return 0;
        }
        if (s[pos] >= 'A' && s[pos] <= 'Z') {
            int x = searching(pos + 1);
            if (x > 9) {
                s[pos] = (x % 10) + '0';
            }
            else {
                s[pos] = x + '0';
            }
            return 1 + x;
        }
        if (s[pos] >= '1' && s[pos] <= '9') {
            if (pos + (s[pos] - '0') < n) {
                int x = searching(pos + (s[pos] - '0'));
                s[pos] -= 1;
                return 1 + x;
            }
            else {
                int x = searching(pos + 1);
                s[pos] -= 1;
                return 1 + x;
            }
        }
        return 0;
    }
    
    int main() {
        string input;
        while (true) {
            cin >> input;
            if (input == "ENDOFINPUT") {
                break;
            }
            cin >> n;
            cin >> s;
            cin >> input;
    
            searching(0);
            cout << s << endl;
        }
        return 0;
    }
    • 1

    信息

    ID
    303
    时间
    1000ms
    内存
    256MiB
    难度
    10
    标签
    递交数
    1
    已通过
    1
    上传者