题解:洛谷 P3879 [TJOI2010] 阅读理解

【题目来源】

洛谷:[P3879 TJOI2010] 阅读理解 - 洛谷

【题目描述】

英语老师留了 \(N\) 篇阅读理解作业,但是每篇英文短文都有很多生词需要查字典,为了节约时间,现在要做个统计,算一算某些生词都在哪几篇短文中出现过。

【输入】

第一行为整数 \(N\) ,表示短文篇数,其中每篇短文只含空格和小写字母。

按下来的 \(N\) 行,每行描述一篇短文。每行的开头是一个整数 \(L\) ,表示这篇短文由 \(L\) 个单词组成。接下来是 \(L\) 个单词,单词之间用一个空格分隔。

然后为一个整数 \(M\) ,表示要做几次询问。后面有 \(M\) 行,每行表示一个要统计的生词。

【输出】

对于每个生词输出一行,统计其在哪几篇短文中出现过,并按从小到大输出短文的序号,序号不应有重复,序号之间用一个空格隔开(注意第一个序号的前面和最后一个序号的后面不应有空格)。如果该单词一直没出现过,则输出一个空行。

【输入样例】

3
9 you are a good boy ha ha o yeah
13 o my god you like bleach naruto one piece and so do i
11 but i do not think you will get all the points
5
you
i
o
all
naruto

【输出样例】

1 2 3
2 3
1 2
3
2

【解题思路】

image

【算法标签】

《洛谷 P3879 阅读理解》 #字符串# #哈希,hash# #字典树,Trie# #各省省选# #天津# #2010#

【代码详解】

#include <bits/stdc++.h>
using namespace std;

int n, m, q;  // n: 集合数量, m: 每个集合的元素个数, q: 查询次数
string s;     // 临时存储输入字符串
map<string, set<int>> a;  // 使用map存储每个字符串出现的集合编号

int main()
{
    // 输入集合数量
    cin >> n;
    
    // 处理每个集合
    for (int i = 1; i <= n; i++) 
    {
        // 输入当前集合的元素个数
        cin >> m;
        
        // 处理当前集合的每个元素
        for (int j = 1; j <= m; j++) 
        {
            cin >> s;
            // 将当前集合编号添加到字符串对应的set中
            a[s].insert(i);
        }
    }

    // 输入查询次数
    cin >> q;
    
    // 处理每个查询
    for (int i = 1; i <= q; i++) 
    {
        cin >> s;
        // 获取该字符串出现的所有集合编号
        set<int> se = a[s];
        
        // 输出结果
        for (set<int>::iterator is = se.begin(); is != se.end(); is++)
        {
            cout << *is << " ";
        }
        cout << endl;
    }

    /* 调试代码:打印整个map的内容
    for (map<string, set<int>>::iterator it = a.begin(); it != a.end(); it++) 
    {
        cout << it->first << " ";
        set<int> se = it->second;
        for (set<int>::iterator is = se.begin(); is != se.end(); is++) 
        {
            cout << *is << " ";
        }
        cout << endl;
    }
    */

    return 0;
}

【运行结果】

3
9 you are a good boy ha ha o yeah
13 o my god you like bleach naruto one piece and so do i
11 but i do not think you will get all the points
5
you
1 2 3
i
2 3
o
1 2
all
3
naruto
2
posted @ 2026-02-18 19:55  团爸讲算法  阅读(3)  评论(0)    收藏  举报