跳到正文

题解

题解:P3879 [TJOI2010] 阅读理解

yongshao约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年7月25日
收录
2026年11月29日
更新
2026年11月29日
篇幅
约 4 分钟
题目
P3879

版本

  1. v1当前

翻遍了题解区,大佬们的解决方法五花八门,map套bitset,套array等等。

为什么非得多加一个数据结构呢?其实我们可以开多个哈希表,每个哈希表中用bool来记录这篇文章中含那些单词。

先放AC代码

C++
#include<bits/stdc++.h>
#define maxn 1010
using namespace std;
unordered_map<string,bool> mp[maxn];
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int l;
        cin>>l;
        while(l--)
        {
            string s;
            cin>>s;
            mp[i][s]=1;
        }
    }
    int m;
    cin>>m;
    while(m--)
    {
        string s;
        cin>>s;
        for(int i=1;i<=n;i++)
            if(mp[i].find(s)!=mp[i].end())
                cout<<i<<" ";
        cout<<"\n";
    }
    return 0;
}

简单说下两种使用map或unordered_map方式的不同之处:

dalao们的题解是只开一个哈希表,哈希表内,每个字符串对应其所在文章

而我的则是对每篇文章开一个哈希表,每个哈希表只需要存储这个单词在不在这篇文章里就行了。对于这件事,甚至都用不到那个bool——哈希表有一个性质:没有访问过的Key不存在。find它则会返回end指针。

这样,我们只需要比较指针是不是end——如果不是,那么说明这个单词在这篇文章访问过了;是end,则说明这个单词压根没被访问。(那个bool也就用不上了,也就是你写mp[i][s]mp[i][s];就行,这就算访问。)

这还会带来一个好处:没被访问过的节点既然不存在,那么也根本不会占内存。我那AC代码最大4MB

如果你听说过势能分析时间的话,这里用势能分析空间同理:只有出现过的单词会开辟内存,也就是最多N×LN\times L个单词会占空间

最后,如果你追求快一点的速度(实测并没有快太多),可以使用gp_hash_table

另外实测把gp两个字换成cc还能再快点,但还是推荐gp

C++
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>
#define maxn 1010
using namespace std;
using namespace __gnu_pbds;
gp_hash_table<string,bool> mp[maxn];
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int l;
        cin>>l;
        while(l--)
        {
            string s;
            cin>>s;
            mp[i][s]=1;
        }
    }
    int m;
    cin>>m;
    while(m--)
    {
        string s;
        cin>>s;
        for(int i=1;i<=n;i++)
            if(mp[i].find(s)!=mp[i].end())
                cout<<i<<" ";
        cout<<"\n";
    }
    return 0;
}
原文