hdu 1671

题目大意:

  给你一连串的电话号码,确定没有一个电话号码是另一个电话号码的前缀:

字典树的题,没什么好说的,可以用来练手;

这道题需要注意的是回收空间;

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>

using namespace std;

struct Node{
    int cnt;
    Node *next[10];
    Node(){
        cnt = 0;
        for(int i = 0; i < 10; ++i)
            next[i] = nullptr;
    }
};

string s[10010];
Node *root;

void remove_tree(Node *u){
    if(u == nullptr) return ;
    for(int i = 0; i < 10; ++i)
        remove_tree(u->next[i]);
    delete u;
}

int main()
{
    int T, n;
    scanf("%d", &T);
    while(T--){
        int ok = 1;
        root = new Node;
        scanf("%d", &n);
        for(int i = 0; i < n; ++i){
            cin >> s[i];
            Node *p = root;
            for(unsigned j = 0; j < s[i].size(); ++j){
                int t = s[i][j] - '0';
                if(p->next[t] == nullptr)
                    p->next[t] = new Node;
                p = p->next[t];
                p->cnt++;
            }
        }
        for(int i = 0; i < n; ++i){
            Node *p = root;
            for(unsigned j = 0; j < s[i].size(); ++j){
                int t = s[i][j]-'0';
                p = p->next[t];
            }
            if(p->cnt > 1){
                ok = 0;
                break;
            }
        }
        if(ok)
            printf("YES\n");
        else
            printf("NO\n");
        remove_tree(root);  
      //回收空间的时候我多加了一句delete root,然后找了两天的bug;
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值