zoukankan      html  css  js  c++  java
  • 2015 UESTC Training for Search Algorithm and String N 韩爷的梦

    韩爷的梦

    Time Limit: 200/100MS (Java/Others)     Memory Limit: 1300/1300KB (Java/Others)
     

    一天,韩爷去百度面试,面试官给了他这么一个问题。

    给你2万个字符串,每个字符串长度都是100,然后把2万个字符串丢入一个 set< string >g 中,问最终set里含有多少个元素?
    g 是一个用来存储字符串、具有去重功能的容器,即相同字符串在 g 中只能保留一个。
    两个字符串相等,当且仅当,长度一样且对应位置的字符都一样。

    韩爷前晚没睡好,随手写了一个程序交给面试官,然后就gg了。

    #include<iostream>
    #include<string>
    #include<set>
    using namespace std;
    string s;
    set<string>g;
    int main(){
        for(int k=1;k<=20000;k++){
            cin>>s;
            g.insert(s);
        }
        cout<<g.size()<<endl;
        return 0;
    }

    韩爷醒来之后,发现这只是一个梦(还好只是个梦)。他回忆起梦中的面试官给他的内存限制和时间限制非常低,这么做肯定过不了,那么,现在你不在梦中,你能解决这个问题么?

    Input

    单case

    每个case有且只有2万行,每一行包含一个字符串,每行字符串的长度都为100 (样例除外)

    字符集:大写英文字母(A-Z),小写英文字母(a-z),数字(0-9)

    Output

    输出一个整数,表示最终set里含有多少个元素。

    Sample input and output

    Sample InputSample Output
    aaAa
    aaAa
    bbbb
    1234
    bbbb
    bbbb
    ee09
    4

    Hint

    解题思路:

      20W个单词,每个单词的长度为100,现在要问的是输入20W个单词,问有多少个不重复的单词。

    以前做过一个数据量小的,上来后,直接开了个set<string>S,然后把输入的所有单词都丢进set里面,

    得到了最后 size。

      这样果断不行,所以利用字符串hash来搞,来写一个hash函数 hash[i] = ( hash[i-1]*p+idx(s[i]))%mod;

    然后把他扔进一个数组里面,用unique去掉那些重复的就行了。

    代码:

     1 # include<cstdio>
     2 # include<iostream>
     3 # include<algorithm>
     4 
     5 using namespace std;
     6 
     7 # define MAX 20000+4
     8 
     9 int hashh[MAX];
    10 
    11 char str[MAX];
    12 
    13 void hashinit( int & x )
    14 {
    15     x = 0x7FED7FED;
    16     int p = 1e6+7;
    17     int mod = 1e9+7;
    18     for ( int i = 0;i < 100;i++ )
    19     {
    20         int val = str[i];
    21         x = (x*p+val)%mod;
    22     }
    23 }
    24 
    25 int main(void)
    26 {
    27     int cnt = 0;
    28     const int n = 20000;
    29     for ( int i = 0;i < n;i++ )
    30     {
    31         scanf("%s",str);
    32         int q1;
    33         hashinit(q1);
    34         hashh[cnt++] = q1;
    35     }
    36     sort(hashh,hashh+cnt);
    37     int res = unique(hashh,hashh+cnt)-hashh;
    38     printf("%d
    ",res);
    39 
    40 
    41     return 0;
    42 }
  • 相关阅读:
    帝国cms在任意位置调用指定id的栏目名称和链接
    Sublime Text 2中前端必备的常用插件
    sublime text 2代码片段(Snippet)功能的使用
    写好PPT的四大要点
    解码郭台铭语录,50句你应该知道的“郭台铭语录”
    java.sql.SQLSyntaxErrorException: Table 'demo.hibernate_sequence' doesn't exist
    Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.example.demo.domain.DeptInfo
    com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的区别
    Spring Boot引入Lombok
    Spring Boot(二)jpa操作数据库
  • 原文地址:https://www.cnblogs.com/wikioibai/p/4524739.html
Copyright © 2011-2022 走看看