百练+Trie数+求字符串前缀的经典模板

点击打开链接
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>
#include<cstring>
#include<string>
#include<math.h>
#include<algorithm>
#define LL long long
#define inf 0x3f3f3f3f
#define mod 1e9+7
using namespace std;
struct Node{
    struct Node *next[10];///只有0-9这10个
    int isCover, isEnd;
};
int ok;
void clean(Node *p)
{
    memset(p->next,0,sizeof(p->next));
    p->isCover = p->isEnd = 0;
}
void Insert(char *str, Node *root)
{
    Node *p = root;
    int id;
    while(*str){
        id = *str - '0';
        if(p->next[id] == NULL){
            p->next[id] = (Node *)malloc(sizeof(Node));
            clean(p->next[id]);
        }
        p = p->next[id];
        if(p->isEnd) ok = 0;///有前缀了,这里标记一波。
        ++p->isCover;
        ++str;///字符串移动一波。
        }
    if(p->isCover > 1) ok = 0;
    p->isEnd = 1;///字符串最后一个字符的附加信息标记。
}
void DELETE(Node *p)
{
    for(int i = 0; i < 10; ++i)///典型递归模板,10个表示0-9
        if(p->next[i]) DELETE(p->next[i]);
    free(p);
}
int main()
{
    int t, n;
    char str[12];
    scanf("%d", &t);
    while(t--){
        Node *root = (Node *)malloc(sizeof(Node));
        scanf("%d", &n);
        clean(root); ok = 1;
        while(n--){
            scanf("%s", str);
            if(ok) Insert(str, root);
        }
        printf(ok ? "YES\n" : "NO\n");///YES表示没有前缀,NO表示有前缀。
        DELETE(root);
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值