zoj 2876 Phone List

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ZERO 0
const int  FIRST_CHAR = '0';
char  num[11111][20] ;
typedef struct node
{
    struct node *child[20]; /* 存储下一个字符 */
    int n; /* 记录当前单词出现的次数 */
}node, *Node;

Node root; /* 字典树的根结点(不存储任何字符) */
/* 插入单词 */
void insert(char *str)
{
    int i, index, len;
    Node current = NULL, newnode = NULL;
    
    len = strlen(str);
    
    current = root; /* 开始时当前的结点为根结点 */
    for (i = 0; i < len; i++) /* 逐个字符插入 */
    {
        index = str[i] - FIRST_CHAR; /* 获取此字符的下标 */
        if (current->child[index] != NULL) /* 字符已在字典树中 */
        {
            current = current->child[index]; /* 修改当前的结点位置 */
            (current->n)++; /* 当前单词又出现一次, 累加 */
        }
        else /* 此字符还没出现过, 则新增结点 */
        {
            newnode = (Node)calloc(1, sizeof(node)); /* 新增一结点, 并初始化 */
            current->child[index] = newnode;
            current = newnode; /* 修改当前的结点的位置 */
            current->n = 1; /* 此新单词出现一次 */
        }
    }
}
/* 在字典树中查找单词 */
int find_word(char *str)
{
    int i, index, len;
    Node current = NULL;
    
    len = strlen(str);
    
    current = root; /* 查找从根结点开始 */
    for (i = 0; i < len; i++)
    {
        index = str[i] - FIRST_CHAR; /* 获取此字符的下标 */
        if (current->child[index] != NULL) /* 当前字符存在字典树中 */
        {
            current = current->child[index]; /* 修改当前结点的位置 */
        }
        else
        {
            return ZERO; /*还没比较完就出现不匹配, 字典树中没有此单词*/
        }
    }
    
    if((current->n)>1) return  1;
    return 0;   
}
void release(Node root)
{
     int i;
     
      if (NULL == root)
    {
        return;
    }
    
    for (i = 0; i < 20; i++)
    {
        if ( root->child[i] != NULL )
        {
            release( root->child[i] );
        }
    }
    
    free( root );
    root = NULL;
}

int main()
{
    int i,n,m,check;
    
   
     scanf("%d",&n);
    while(n--)
    {
        scanf("%d",&m);
         root = (Node)calloc(1, sizeof(node));
        for(i=0;i<m;i++)
        {
          scanf("%s",num[i]);
          insert(num[i]);
        }
        check=0;
       for(i=0;i<m;i++)
        {
           if(find_word(num[i])) 
            {
              check=1;
              break;
            }
        }
        if(check==1) 
          printf("NO\n");
        if(check==0)
          printf("YES\n");
        release(root);
    }
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值