正在载入在线练习界面,本页内容可直接阅读…
AK CSP › CSP-S 2020 第一轮真题 › 第32题
CSP-S 2020 第一轮 第32题:己知当输入为 0123 3210 1 时输出为 4,当输入为 0123
题目
#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;
}本小题
(4 分)己知当输入为 0123\n3210\n1 时输出为 $4$,当输入为 012345\n543210\n1 时输出为 $14$,当输入为 01234567\n76543210\n1 时输出为 $28$,则当输入为0123456789ab\nba9876543210\nl 输出为 ( )。其中 \n 为换行符。
选项
- A. 56
- B. 84
- C. 102
- D. 68
答案
D
题解
第⑤题选 D.68。最后输入的 l 应理解为数字 1。
当 m=1 时,从初始字符串出发,有两种操作:
LtoR(st, 1, len-1):将除首字符外的部分循环左移一位。RtoL(st, 0, 1):交换前两个字符。
程序从两端搜索,相遇时输出两边的步数之和。
这道选择题的快捷做法,是观察题目给出的步数规律:
| 字符串长度 | 输出 | 比上一项增加 |
|---|---|---|
| 4 | 4 | — |
| 6 | 14 | 10 |
| 8 | 28 | 14 |
| 10 | 推得 46 | 18 |
| 12 | 推得 68 | 22 |
长度每增加 \(2\),步数的增量依次为 \(10,14,18,22\),每次增加 \(4\)。所以长度为 \(12\) 时: \[ 28+18+22=\boxed{68}. \]
也可以把这一规律写成 \(f(n)=\frac{n^2}{2}-4\),代入 \(n=12\) 得到同样结果。
注意:这是利用样例提示归纳规律的解题方法,单凭三组数据本身不能严格证明通式。
真题版权归 CCF 所有,本站仅用于非商业教学用途。页面加载后可直接在线作答,作答记录保存在本浏览器或账号中。 京ICP备2026056990号-1
京公网安备11010502062986号