POJ-2503-查单词

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值