您的位置:首页 > 其它

HDU 1305 Immediate Decodability(与1671类似)

2015-08-14 10:37 375 查看
题意:在多个字符串里寻找,若他们至少有一个串是另一个串的前缀,则按题目要求输出

思路:建立字典树,因为只有0 1两数,数组开2大就行,判断是前缀的方法:每次插入一个字符串,在字典树中查询,若当到达已经存在了的字符串,即cur->cnt==1 ,也就是插入字符串的前缀,或者在字典树中能够找到插入的字符串

#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<sstream>
#include<fstream>
#include<vector>
#include<map>
#include<stack>
#include<list>
#include<set>
#include<queue>
#define LL long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1 | 1
using namespace std;
const int child_size=2;
struct node
{
    int num,id;
    node *next[child_size];
    node() { num=0;id=0;memset(next,0,sizeof(next));}
};
node *p,*root;
string str[10005];
void Insert(string s)
{
    p=root;
    for(int i=0;i<s.size();i++)
    {
        int id=s[i]-'0';
        if(p->next[id]==0) p->next[id]=new node();
        p=p->next[id];
        //p->num++;
    }
    p->num=1;
}
int Query(string s)
{
    p=root;
    for(int i=0;i<s.size();i++)
    {
        int id=s[i]-'0';
        if(p->next[id]==0) return 1;
        p=p->next[id];
        if(p->num==1&&(i<s.size()-1)) return 0;
    }
   // if(p->num>1) return 0;
    return 1;
}
void Delete(node *rt)
{
    for(int i=0;i<child_size;i++)
    {
        if(rt->next[i])
        {
            Delete(rt->next[i]);
            delete(rt->next[i]);
        }
    }
}
int main()
{
    int n,t,Case=1;
    cin.sync_with_stdio(false);
    //cin>>t;
    while(cin>>str[0]&&str[0]!="9")
    {
        int i=1;
        root=new node();
        int flag=0;
        Insert(str[0]);
        while(cin>>str[i++]&&str[i-1]!="9") Insert(str[i-1]);
        for(int j=0;j<i-1;j++)
        {
            if(!Query(str[j]))
            {
                flag=1;
                break;
            }
        }
        if(flag) cout<<"Set "<<Case++<<" is not immediately decodable"<<endl;
        else cout<<"Set "<<Case++<<" is immediately decodable"<<endl;
        Delete(root);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: