• HDU 5687 Problem C(字典树查找删除)


    Problem Description
    度熊手上有一本神奇的字典,你可以在它里面做如下三个操作:

    1、insert : 往神奇字典中插入一个单词

    2、delete: 在神奇字典中删除所有前缀等于给定字符串的单词

    3、search: 查询是否在神奇字典中有一个字符串的前缀等于给定的字符串

    Input
    这里仅有一组测试数据。第一行输入一个正整数N(1≤N≤100000),代表度熊对于字典的操作次数,接下来N行,每行包含两个字符串,中间中用空格隔开。第一个字符串代表了相关的操作(包括: insert, delete 或者 search)。第二个字符串代表了相关操作后指定的那个字符串,第二个字符串的长度不会超过30。第二个字符串仅由小写字母组成。

    Output
    对于每一个search 操作,如果在度熊的字典中存在给定的字符串为前缀的单词,则输出Yes 否则输出 No。

    Sample Input
    5
    insert hello
    insert hehe
    search h
    delete he
    search hello

    Sample Output
    Yes
    No

    Source
    2016"百度之星" - 资格赛(Astar Round1)

    题意:

    题解:

    很裸的一道字典树的题。但是这道题很容易卡内存,在每个结点记录一下以当前字母结尾的前缀数。

    #include<iostream>
    #include<string>
    #include<cstring>
    using namespace std;
    int tot,n;
    const int maxn=3e6+5;
    struct node
    {
    	int next[27];
    	int cnt;
    	void init()
    	{
    		cnt=0;//记录着字典树中每层以当前字符串为前缀的字符串的数目
    		memset(next,-1,sizeof(next));
    	}
    }trie[maxn]; 
    void insert(string s)
    {
    	int cur=0;
    	for(int i=0;i<s.length();i++)
    	{
    		int temp=s[i]-'a';
    		int next=trie[cur].next[temp];
    		if(next==-1)
    		{
    			next=++tot;
    			trie[next].init();
    			trie[cur].next[temp]=next;
    		}
    		cur=next;
    		trie[cur].cnt++;
    	}
    }
    bool find(string s)
    {
    	int cur=0;
    	for(int i=0;i<s.length();i++)
    	{
    		int tmp=s[i]-'a';
    		int next=trie[cur].next[tmp];
    		if(next==-1)
    			return false;
    		cur=next;
    	}
    	return trie[cur].cnt>0;//该字符串为前缀的数目>0
    }
    void del(string s)
    {
    	int cur=0;
    	for(int i=0;i<s.length();i++)//删除前,首先判断是否存在该字符串
    	{
    		int tmp=s[i]-'a';
    		int next=trie[cur].next[tmp];
    		if(next==-1)
    			return ;
    		cur=next;
    	}
    	int tail;
    	cur=0;
    	for(int i=0;i<s.length();i++)//删除时不清空结点信息 
    	{
    		int tmp=s[i]-'a';
    		int next=trie[cur].next[tmp];
    		tail=cur;
    		cur=next;
    		trie[cur].cnt--;//字符串为前缀的数目减一
    	}
    	trie[cur].init();
    	trie[tail].next[s[s.length()-1]-'a']=-1;
    }
    int main()
    {
    	cin>>n;
    	string op,s;
    	trie[0].init();
    	while(n--)
    	{
    		cin>>op>>s;
    		if(op=="insert")
    			insert(s);
    		else if(op=="search")
    			if(find(s))
    				cout<<"Yes"<<endl;
    			else
    				cout<<"No"<<endl;
    		else
    			del(s);
    	}
    	return 0;
    }
  • 相关阅读:
    react-redux-reducer
    react-redux-action
    node-express-2-jade
    node-express-1
    vuex-Module
    vuex-Action(异步)
    vuex-Mutation(同步)
    vuex-getter
    vuex-state
    ##DAY7 UINavigationController
  • 原文地址:https://www.cnblogs.com/orion7/p/7635909.html
Copyright © 2020-2023  润新知