本文共 801 字,大约阅读时间需要 2 分钟。
题目
制作一个数据结构,支持静态询问字符串x出现在哪些短文中并去重。
思路
首先,我们需要一个高效的数据结构来存储字符串x及其出现的位置。为了实现查找功能,我们可以使用std::map来存储键为字符串x,值为一个std::set
的映射。std::set不仅可以自动去重,还能快速查找元素是否存在,这样我们就能快速判断x是否出现在文本中。通过这种方式,我们可以在O(log n)的时间复杂度内完成查找和插入操作。> a;int n, m;string x;int main() { cin >> n; for (int i = 0; i < n; ++i) { cin >> m; for (int j = 0; j < m; ++j) { cin >> x; a[x].insert(i + 1); } } cin >> n; for (int i = 0; i < n; ++i) { cin >> x; if (a.find(x) != a.end()) { for (set ::iterator it = a[x].begin(); it != a[x].end(); ++it) { cout << *it << ' '; } } } return 0;}#include#include #include
转载地址:http://vfye.baihongyu.com/