HDU1251 统计难题(字典树)

题意分析

用字典树,保存前缀个数,每次插入的时候加一。查询时直接查询到待查询前缀的最后一个字母,如果为前缀,那么一定保存过,否则肯定没保存过,答案就为0.

每次查询是可以认为每次插入和查询都是O(len(str))的,因为每次查询只需要沿着字典树走下来就好了。需要注意的是内存开销。
题目没说总共有多少个待查询子串,一开始一直超时,我以为是写挂了。
假设要插入 n 个串,串最长为 l e n m a x ,最差情况,需要开的空间为, n l e n m a x , 即认为每个字符都不同。

代码总览

#include <cstdio>
#include <cstring>
#define mem(x,y) memset(x,y,sizeof x)
#define rep(i,a,b) for (int i = a; i<=b; ++i)
using namespace std;
const int nmax = 1e6 + 10;
const int INF = 0x3f3f3f3f;
typedef long long ll;
typedef double db;
#define sigma_size 26
#define maxlength 500000
typedef struct {
    int ch[maxlength][sigma_size];
    int val[maxlength];
    int sz;
    init() { sz = 1; memset(ch[0], 0, sizeof(ch[0])); }
    inline int idx(char c) { return c - 'a'; }

    void insert(char *s, int v) {
        int u = 0, n = strlen(s);
        for (int i = 0; i < n; i++) {
            int c = idx(s[i]);
            if (ch[u][c] == 0) {
                memset(ch[sz], 0, sizeof(ch[sz]));
                ch[u][c] = sz++;
            }
            u = ch[u][c];
            val[u] ++;
        }
    }
    int search(char *s, int v) {
        int u = 0, n = strlen(s), c;
        for (int i = 0; i < n; i++) {
            c = idx(s[i]);
            if (ch[u][c] == 0) return 0;
            u = ch[u][c];
        }
        return val[u];
    }
} Trie;
Trie trie;
int main() {
    // freopen("in.txt", "r", stdin);
    char str[105];
    trie.init();
    while (gets(str) && strcmp(str, "") != 0) trie.insert(str, 1);
    while (scanf("%s", str) != EOF) printf("%d\n", trie.search(str, 1));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/pengwill97/article/details/80432999
今日推荐