P3879 [TJOI2010]阅读理解

\(\color{#0066ff}{ 题目描述 }\)

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

\(\color{#0066ff}{输入格式}\)

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

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

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

\(\color{#0066ff}{输出格式}\)

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

\(\color{#0066ff}{输入样例}\)

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

\(\color{#0066ff}{输出样例}\)

1 2 3
2 3
1 2
3
2

\(\color{#0066ff}{数据范围与提示}\)

对于30%的数据,1 ≤ M ≤ 1,000

对于100%的数据,1 ≤ M ≤ 10,000,1 ≤ N ≤ 1000

每篇短文长度(含相邻单词之间的空格) ≤ 5,000 字符,每个单词长度 ≤ 20 字符

\(\color{#0066ff}{ 题解 }\)

对所有单词建立Trie树,每个点维护一个set,代表属于哪一行

匹配到的时候扫一遍set就行了

#include<bits/stdc++.h>
#define LL long long
LL in() {
    char ch; LL x = 0, f = 1;
    while(!isdigit(ch = getchar()))(ch == '-') && (f = -f);
    for(x = ch ^ 48; isdigit(ch = getchar()); x = (x << 1) + (x << 3) + (ch ^ 48));
    return x * f;
}
using std::set;
struct Trie {
protected:
    struct node {
        node *ch[26];
        set<int> s;
        node() {
            memset(ch, 0, sizeof ch);
            s.clear();
        }
        void *operator new (size_t) {
            static node *S = NULL, *T = NULL;
            return (S == T) && (T = (S = new node[1024]) + 1024), S++;
        }
    };
    node *root;
public:
    Trie() { root = new node(); }
    void ins(char *s, int id) {
        node *o = root;
        for(char *p = s; *p; p++) {
            int pos = *p - 'a';
            if(!o->ch[pos]) o->ch[pos] = new node();
            o = o->ch[pos];
        }
        o->s.insert(id);
    }
    void query(char *s) {
        node *o = root;
        for(char *p = s; *p; p++) {
            int pos = *p - 'a';
            if(o->ch[pos]) o = o->ch[pos];
            else goto noans;
        }
        for(auto &k : o->s) printf("%d ", k);
        noans:;
        puts("");
    }
}T;
char s[500];
int main() {
    int n = in();
    for(int i = 1; i <= n; i++) {
        int k = in();
        for(int j = 1; j <= k; j++) {
            scanf("%s", s);
            T.ins(s, i);
        }
    }
    for(int m = in(); m --> 0;) {
        scanf("%s", s);
        T.query(s);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/olinr/p/10248840.html