hdu 1305 Immediate Decodability

点击打开链接hdu1305


思路:字典树

分析:
1 题目要求的是是否有一个字符串作为其它字符串的前缀
2 利用字典树的性质在插入的时候就可以判断某一个字符串是否是其它字符串或当前字符串是其它字符串的前缀
3 多组数据利用静态分配不能用动态分配。

代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;

#define MAXN 1000010
#define N 15

int cnt;
struct Trie{
   bool flag;
   Trie *child[N];
}trie[MAXN];
Trie *root;

/*静态分配空间*/
Trie* newTrie(){
   trie[cnt].flag = false;
   for(int i = 0 ; i < N ; i++)
      trie[cnt].child[i] = NULL;
   return &trie[cnt++];
}

/*字典树的插入*/
bool insert(char *str){
    Trie *s = root;
    int len = strlen(str);
    for(int i = 0 ; i < len ; i++){
       int num = str[i]-'0';
       if(s->child[num] == NULL)
         s->child[num] = newTrie();
       s = s->child[num];
       if(s->flag == true)
          return false;
    }
    for(int i = 0 ; i < N ; i++){
       if(s->child[i])
         return false;
    }
    s->flag = true;
    return true;
}

int main(){
   int mark , Case;
   char ch[N];
   Case = 1;
   while(scanf("%s" , ch) != EOF){
       cnt = 0;
       root = newTrie();
       mark = 1;
       if(!insert(ch))
          mark = 0;
       while(scanf("%s" , ch) && strcmp(ch , "9") != 0){
          if(mark){
            if(!insert(ch))
              mark = 0;
          }
       }
       if(mark)
         printf("Set %d is immediately decodable\n" , Case++);
       else
         printf("Set %d is not immediately decodable\n" , Case++);
   }
   return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值