HDU 1251 统计难题

- HDU 1251 -

统计难题

ime Limit: 4000/2000 MS (Java/Others) | Memory Limit: 131070/65535 K (Java/Others)

题意:

给出一张单词表,每行一个单词,单词的长度不超过10 (只有小写字母组成,不会有重复的单词出现),要求统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
注意:本题只有一组测试数据,处理到文件结束.

数据范围:

单词的长度不超过10

解题思路:

map函数 字典树

刚开始做这题的时候其实是被它的输入问题給卡住了,因为这题是通过一个空行来划分单词表和问题的,但我总是不能准确地作出判断来划分,后来看了 discuss 得知了一些判断方法。
这道题是我用 map 函数和字典树做的第一道题,可以说是我了解并初步学会使用 map 函数和字典树的入门题吧,值得纪念O(∩_∩)O~

代码:

① map函数:

Exe.Time : 764MS | Exe.Memory : 22532K

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <map>
#include <cstring>
using namespace std;
map<string,int> mp;

int main()
{
    string word="";
    char c,ant[11];
    
    while(1){
        c=getchar();
        if(c=='\n'){
            c=getchar();
            word="";
        }
        if(c=='\n')
            break;
        word+=c;
        mp[word]++;
    }
    while(cin>>ant){
        cout<<mp[ant]<<endl;
    }
    return 0;
} 

② 字典树:

Exe.Time : 124MS | Exe.Memory : 40916K

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
using namespace std;
#define INF 0x3f3f3f
#define zero 1e-7

typedef long long ll;
const int N=1e5+7;
int tree[26*N][26]={0};//Exe.Time 124MS Exe.Memory 40916K
int cnt[26*N]={0};//记节点出现次数来代表字符串前缀出现次数
int k=0;//节点标号

void inSert(char *s) {
    int p=0, len=strlen(s);
    for(int i=0; i<len; i++) {
        int c=s[i]-'a';
        if(!tree[p][c])
            tree[p][c]=++k;
        //printf("cnt[%d][%d]=%d\t", p, c, cnt[p][c]);
        p=tree[p][c];
        cnt[p]++;
    }
    return ;
}

int Search(char *s) {
    int p=0, len=strlen(s);
    for(int i=0; i<len; i++) {
        int c=s[i]-'a';
        if(!tree[p][c]) return 0;
        p=tree[p][c];
    }
    return cnt[p];
}

int main() {
    char s[50];
//    memset(cnt, 0, sizeof(cnt));
//    memset(tree, 0, sizeof(tree));
//事实证明,cnt、tree数组的清零不能用memset,否则会Memory Limit
//Exe.Time 109MS  Exe.Memory 75424KExceeded
    while(gets(s)) {
        if(!s[0])
        //或if(!strlen(s))
        //或if(!strcmp(s, "\0"))
            break;
        inSert(s);
    }
    while(gets(s))
        printf("%d\n", Search(s));
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值