hdu 1305 Immediate Decodability

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

点击打开链接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;
}




目录
相关文章
|
5月前
|
Java
hdu 2503 a/b + c/d
hdu 2503 a/b + c/d
25 0
|
机器学习/深度学习 人工智能
|
算法 Java 文件存储
|
人工智能
HDU1106
为了给学弟学妹讲课,我又水了一题…… 1: import java.util.*; 2: import java.io.*; 3: 4: public class HDU1106 5: { 6: public static void main...
857 0