http://poj.org/problem?id=2503
好多方法做
map 900ms / hash+sort+二分 400ms / hash查找 400ms /trie 361ms 除了第一个后面都差不大多。。当然和实现有关
代码就贴个trie吧
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include<stack>
using namespace std;
#include <fstream>
typedef unsigned __int64 uLL ;
const int maxnode = 1000005;
struct trie
{
int ch[maxnode][26];
int val[maxnode];
int sz;
string ss[maxnode];
void init()
{
sz=1;
val[0]=0; //可不需要
memset(ch[0],0,sizeof(ch[0]));
}
inline int idx(char c) {return c-'a';}
void insert(char *s,string& sss)
{
int u=0,n=strlen(s),i;
for (i=0;i<n;i++)
{
int c=idx(s[i]);
if (!ch[u][c])
{
memset(ch[sz],0,sizeof(ch[sz]));
val[sz]=0;
ch[u][c]=sz++;
}
u=ch[u][c];
}
val[u]=n; //标记当前单词权值(暂且当作字符串结尾标记)
ss[u]=sss;
}
string query_if(char *s) //查找当前单词是否存在,本题用不上
{
int u=0,n=strlen(s),i;
for (i=0;i<n;i++)
{
int c=idx(s[i]);
if (!ch[u][c])
return "";
else
{
u=ch[u][c];
}
}
return ss[u];
}
};
trie tp;
int main()
{
int i;
//#include <fstream>
// ifstream cin("F:\\duipai\\1.in");
tp.init();
string line;
int ok=0;
string s1,s2;
while(getline(cin,line))
{
if (line=="") break;
for (i=0;;i++)
if (line[i]==' ') break;
s1=line.substr(0,i);
s2=line.substr(i+1,line.length());
tp.insert((char*)s2.c_str(),s1);
}
while(getline(cin,line))
{
string ans=tp.query_if((char*)line.c_str());
if (ans!="")
printf("%s\n",ans.c_str());
else
printf("eh\n");
}
return 0;
}