首页 > 其他 > 详细

Hdoj 1251 统计难题 【Hash】

时间:2015-03-22 18:07:50      阅读:195      评论:0      收藏:0      [点我收藏+]

统计难题

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
banana band bee absolute acm ba b band abc
 

Sample Output
2 3 1 0

简单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;
}


Hdoj 1251 统计难题 【Hash】

原文:http://blog.csdn.net/shengweisong/article/details/44539265

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!