【统计难题】【HDU - 1251】【map打表或字典树】【字典树模板】

思路

题意题目为中文题,这里不再过多阐述。
思路1:可以在读入单词表的过程中将单词分解,用map将它一 一记录
思路2:利用字典树,这个方法较快些,下面代码中会分别给出数组和结构体指针两种形式的字典树,指针形式的有时可能会因题目内存限制而导致Memory Limit Exceeded,这时就可选择数组形式的。不过对于本题来说不用担心。

AC代码

代码1:map打表

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
map<string, int> table;
int main()
{
    std::ios::sync_with_stdio(false);
//    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
    table.clear();
    string s;
    while(getline(cin, s))
    {
        if(s[0] == '\0')
            break;
        string ss = "";
        for(int i = 0; i < s.size(); i++)
        {
            ss += s[i];
            table[ss]++;
        }
    }
    while(cin >> s)
    {
        cout << table[s] << endl;
    }
}

代码2:数组形式的字典树

#include<bits/stdc++.h>
using namespace std;
const int maxnode = 400001;
const int maxs = 27;
char s[10 + 10];
int trie[maxnode][maxs] ;
int sum[maxnode] ;
int node = 0;
void inserts(char *t)
{
    int len = strlen(t);
    int cur = 0;
    for(int i = 0; i < len; i++)
    {
        int p = t[i] - 'a';
        if(!trie[cur][p])
            trie[cur][p] = ++node;
        sum[trie[cur][p]]++;
        cur = trie[cur][p];
    }
}
int searchs(char *t)
{
    int len = strlen(t);
    int cur = 0;
    for(int i = 0; i < len; i++)
    {
        int p = t[i] - 'a';
        if(!trie[cur][p])
            return 0;
        cur = trie[cur][p];
    }
    return sum[cur];
}
int main()
{
//    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
    memset(trie, 0, sizeof(trie));
    memset(sum, 0, sizeof(sum));
    while(gets(s) != NULL)
    {
        if(s[0] == '\0')
            break;
        inserts(s);
    }
    while(scanf("%s", s) != EOF)
    {
        cout << searchs(s) << endl;
    }
}

代码3:结构体指针形式的字典树

//#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char s[10+10];
struct Trie
{
    Trie* next[26];
    int sum;
    Trie()
    {
        for(int i = 0; i < 26; i++)
            next[i] = NULL;
        sum = 0;
    }
}root;
void inserts(char *s)
{
    Trie* p = &root;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        int cur = s[i] - 'a';
        if(p->next[cur] == NULL)
        {
            p->next[cur] = new Trie;
        }
        p = p->next[cur];
        p->sum++;
    }
}
int finds(char *s)
{
    Trie* p = &root;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        int cur = s[i] - 'a';
        if(p->next[cur] == NULL)
            return 0;
        else
            p = p->next[cur];
    }
    return p->sum;
}


int main()
{
//    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
    while(gets(s) != NULL)
    {
        if(s[0] == '\0')
            break;
        inserts(s);
    }
    while(scanf("%s", s) != EOF)
    {
        cout << finds(s) << endl;
    }
}
posted @ 2019-08-17 23:27  DIY-Z  阅读(101)  评论(0编辑  收藏  举报