正在载入在线练习界面,本页内容可直接阅读…

AK CSP › CSP-S 2020 第一轮真题 › 第31题

CSP-S 2020 第一轮 第31题:(2.5分)若输入的第一个字符串长度由100个不同的字符构成,第二

阅读程序·单选 · 搜索与图遍历(DFS/BFS) · 答案 D

题目

#include <iostream>
#include <queue>
using namespace std;

const int maxl = 20000000;

class Map {
    struct item {
        string key; int value;
    } d[maxl];
    int cnt;
  public:
    int find(string x) {
        for (int i = 0; i < cnt; ++i)
            if (d[i].key == x)
                return d[i].value;
        return -1;
    }
    static int end() { return -1; }
    void insert(string k, int v) {
        d[cnt].key = k; d[cnt++].value = v;
    }
} s[2];

class Queue {
    string q[maxl];
    int head, tail;
  public:
    void pop() { ++head; }
    string front() { return q[head + 1]; }
    bool empty() { return head == tail; }
    void push(string x) { q[++tail] = x;  }
} q[2];

string st0, st1;
int m;

string LtoR(string s, int L, int R) {
    string t = s;
    char tmp = t[L];
    for (int i = L; i < R; ++i)
        t[i] = t[i + 1];
    t[R] = tmp;
    return t;
}

string RtoL(string s, int L, int R) {
    string t = s;
    char tmp = t[R];
    for (int i = R; i > L; --i)
        t[i] = t[i - 1];
    t[L] = tmp;
    return t;
}

bool check(string st , int p, int step) {
    if (s[p].find(st) != s[p].end())
        return false;
    ++step;
    if (s[p ^ 1].find(st) == s[p].end()) {
        s[p].insert(st, step);
        q[p].push(st);
        return false;
    }
    cout << s[p ^ 1].find(st) + step << endl;
    return true;
}

int main() {
    cin >> st0 >> st1;
    int len = st0.length();
    if (len != st1.length()) {
        cout << -1 << endl;
        return 0;
    }
    if (st0 == st1) {
        cout << 0 << endl;
        return 0;
    }
    cin >> m;
    s[0].insert(st0, 0); s[1].insert(st1, 0);
    q[0].push(st0); q[1].push(st1);
    for (int p = 0;
            !(q[0].empty() && q[1].empty());
            p ^= 1) {
        string st = q[p].front(); q[p].pop();
        int step = s[p].find(st);
        if ((p == 0 &&
                (check(LtoR(st, m, len - 1), p, step) ||
                 check(RtoL(st, 0, m), p, step)))
                ||
                (p == 1 &&
                 (check(LtoR(st, 0, m), p, step) ||
                  check(RtoL(st, m, len - 1), p, step))))
            return 0;
    }
    cout << -1 << endl;
    return 0;
}

本小题

(2.5 分)若输入的第一个字符串长度由 $100$ 个不同的字符构成,第二个字符串是第一个字符串的倒序,输入的 $m$ 为 $0$,则输出为( )。

选项

  • A. 49
  • B. 50
  • C. 100
  • D. -1

答案

D

题解

选 D.-1。

当 m = 0 时,从第一个字符串出发的两种操作是:

  • LtoR(st, 0, len - 1):把首字符移到末尾,也就是整个字符串循环左移一位。
  • RtoL(st, 0, 0):只操作一个字符,字符串不变。

所以,无论操作多少次,都只能得到原字符串的循环移位。

设原字符串为 \[ a_1a_2\cdots a_{100}, \] 其中所有字符都不同。循环移位后,若要让首字符是 \(a_{100}\),只能得到 \[ a_{100}a_1a_2\cdots a_{99}. \] 而目标倒序字符串是 \[ a_{100}a_{99}\cdots a_1. \] 两者第二个字符不同,因此不可能通过这些操作到达目标。

代码从目标字符串进行的反向搜索也是循环移位,两边不会相遇,最终输出 -1。

真题版权归 CCF 所有,本站仅用于非商业教学用途。页面加载后可直接在线作答,作答记录保存在本浏览器或账号中。 京ICP备2026056990号-1 京公网安备11010502062986号