感觉跟HDU1251统计难题没什么区别, 但少考虑了一种情况也让我郁闷了
如:911 9115654这两个串是不符合情况的
还是就是 9115654 和 911也是不合法的(唉...)
记得要释放内存! 因为有多组测试数据, 不同于HDU1251的统计难题只有一组数据...
2010-11-18 20:53:01 Accepted 1671 312MS 3264K 2419 B C Y
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_AMOUNT 10 /* 0~9的长度 */
const int ZERO = 0;
int EXIT; /* EXIT判断存不存在前轰(1 和 0) */
const char FIRST_NUM_CHAR = '0';
typedef struct node { /* 字典树 */
struct node *child[NUM_AMOUNT]; /* 存储数字0~9 */
int index; /* 用于判断此前辍是否存在字典树中 */
}node, *Node;
Node root; /* 字典树根结点(不存储任何元素) */
/* 插入电话号码到字典树中 */
void insert(char *tel)
{
int i, index, len;
Node newnode = NULL, current = NULL; /* 新增结点和当前结点 */
if ('1' == EXIT) /* 存在前辍 */
{
return;
}
len = strlen(tel);
if (ZERO == len) /* 此电话号码为空,无须插入 */
{
return;
}
current = root;
for (i = 0; i < len; i++) /* 逐个数字地插入 */
{
index = tel[i] - FIRST_NUM_CHAR; /* 此数字在字典树的下标 */
if (1 == current->index || (i == len - 1 && current->child[index] != NULL))
{ /* 1== curr...:911 911132654 此两串情况, 反之为: 911132654 911 此情况*/
EXIT = '1';
return;
} /* 存在前辍 */
if (current->child[index] != NULL) /* 此数字已在字典树中 */
{
current = current->child[index]; /* 修改当前位置 */
}
else /* 不存在此数字, 则新增结点 */
{
if ((newnode=(Node)calloc(1, sizeof(node))) == NULL) /* 新结点 */
{
printf("空间分配失败!\n");
exit(-1);
}
current->child[index] = newnode; /* 新增结点 */
current = newnode; /* 修改当前结点 */
}
}
current->index = 1; /* 此号码已插入字典树中 */
}
/* 释放内在 */
void release(Node root)
{
int i;
Node current;
if (NULL == root) /* 此字典树为空, 不需要释放 */
{
return;
}
current = root; /* 当前结点为root */
for (i = 0; i < NUM_AMOUNT; i++)
{
if (current->child[i] != NULL) /* 此子树非空 */
{
release( current->child[i] );
}
}
free( current ); /* 清理资源 */
current = NULL; /* 指针置空 */
}
int main()
{
int cas, phone_amount; /* cas数据组数, 和电话个数*/
char tel[11]; /* 电话号码(最多10位) */
scanf("%d", &cas);
while ( cas-- )
{
scanf("%d", &phone_amount);
if ((root=(Node)calloc(1, sizeof(node))) == NULL)
{
printf("空间分配失败!\n");
exit(-1);
}
EXIT = '0'; /* 开始时不存在前辍 */
while ( phone_amount-- )
{
scanf("%s", tel);
insert( tel );
}
printf("%s\n", EXIT == '1' ? "NO" : "YES");
release( root );
}
return 0;
}