P3955 [NOIP2017 普及组] 图书管理员 题解
思路:
我们可以把图书编码从小到大进行排序,然后根据读者需求码从前往后进行检索,如果符合即为最小的编码。
这里选择使用 string 类,因为 string 类中有一个函数 rfind(), 具体可以参考这篇 CSDN 博客,rfind() 返回为从后往前寻找找到的字符串的第一个字符下标,再根据题目中的读者需求码长度相加,判断是否和图书编号相等以判断是否为末尾。
最终代码如下(剩下看代码):
#include <bits/stdc++.h>
using namespace std;
string book[1050], reader[1050];
bool cmp(string a, string b)
{
// 因为默认排序是说按照字典序排序,我们要按照像数字一样排序
if (a.length() != b.length())
return a.length() < b.length();
return a < b;
}
int main()
{
int n, q;
cin >> n >> q; // 如题意
for (int i = 1; i <= n; i++) {
cin >> book[i];
}
sort(book + 1, book + n + 1, cmp);
for (int i = 1; i <= q; i++) {
int len;
cin >> len >> reader[i];
bool fag = true; // 是否找到
for (int j = 1; j <= n; j++) {
// book[j].rfind(reader[i]) + len上文提到,判断是否在末尾
if (book[j].rfind(reader[i]) + len == book[j].size() && book[j].rfind(reader[i]) != string::npos) { // 特判string::npos,不然会错
cout << book[j] << endl;
fag = false;
break;
}
}
if (fag) {
cout << -1 << endl; // 没有找到
}
}
return 0;
}