Hdoj 1251 统计难题 【Hash】

来源:互联网 发布:无尽的传说2 mac 编辑:程序博客网 时间:2024/05/22 15:22

统计难题

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 20336    Accepted Submission(s): 8868


Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
 

Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

注意:本题只有一组测试数据,处理到文件结束.
 

Output
对于每个提问,给出以该字符串为前缀的单词的数量.
 

Sample Input
bananabandbeeabsoluteacmbabbandabc
 

Sample Output
2310

简单hash,去每一个字符串的第一个字母减去‘a’,作为线索

代码:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <queue>#include <vector>using namespace std;const int M = 26;struct node{    char s[15];    bool operator < (const node &a) const {  //重载,就是在插入vector时排一下序        if(strcmp(s, a.s) <= 0) return 1;        else return 0;    }};vector<node> d[M];int main(){    for(int i = 0; i < 26; ++ i) d[i].clear();    char s[25];    node temp;    while(gets(temp.s), temp.s[0] != '\0'){        d[temp.s[0]-'a'].push_back(temp);    }    /*for(int i = 0; i < 26; i ++){        for(int j = 0; j < d[i].size(); ++ j)            cout << d[i][j].s<<" ";        cout <<endl;    }*/    while(scanf("%s", s) == 1){        int ans = 0, j;        int sss = s[0]-'a';        for(int i = 0; i < d[sss].size(); ++ i){            for(j = 0; j < strlen(s); ++ j){                if(s[j] != d[sss][i].s[j]) break;            }            if(j == strlen(s)) ++ans;        }        printf("%d\n", ans);    }    return 0;}


0 0
原创粉丝点击