poj2503Babelfish(hash);

来源:互联网 发布:反攻击软件 编辑:程序博客网 时间:2024/05/22 15:24

题意:

给你n行单词,每行两个,让你找后面那个是否出现过,出现过就输出前面对应得单词,不然输出ch
n<100000

思路

第一想法快排+二分,但是是hash得专项训练,就没有打快排了,hash也很简单,用字符串hash,强行转换成数字为hash得key,然后就变成普通hash了。

时间复杂度

hash期望O(1),加上单词书为O(n)

const maxn=999987;var  a,hash:array[0..maxn] of string[30];  i,j:longint;  s,t:string[60];procedure insertion(s,t:string[30]);var i,l:longint; k:int64;begin l:=length(s); k:=0; for i:=1 to l do  k:=k*50+ord(s[i]); i:=k mod maxn; while (hash[i]<>'') and (hash[i]<>s) do i:=i mod maxn+1; hash[i]:=s; a[i]:=t;end;function find(s:string[30]):longint;var i,j,l:longint; k:int64;begin k:=0; l:=length(s); for i:=1 to l do  k:=k*50+ord(s[i]); i:=k mod maxn; while (hash[i]<>'') and (hash[i]<>s) do i:=i mod maxn+1; if hash[i]=s then exit(i)              else exit(0);end;begin  a[0]:='eh';  while true do    begin      readln(s);      if s='' then break;      t:=copy(s,1,pos(' ',s)-1);      delete(s,1,pos(' ',s));      insertion(s,t);    end;  while not eof do    begin      readln(s);      writeln(a[find(s)]);    end;end.
0 0
原创粉丝点击