HDOJ1671 字典树入门题+模板程序(指针实现)

Phone List

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 21253    Accepted Submission(s): 7184


Problem Description
Given a list of phone numbers, determine if it is consistent in the sense that no number is the prefix of another. Let’s say the phone catalogue listed these numbers:
1. Emergency 911
2. Alice 97 625 999
3. Bob 91 12 54 26
In this case, it’s not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob’s phone number. So this list would not be consistent.
 

Input
The first line of input gives a single integer, 1 <= t <= 40, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 <= n <= 10000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits.
 

Output
For each test case, output “YES” if the list is consistent, or “NO” otherwise.
 

Sample Input

2 3 911 97625999 91125426 5 113 12340 123440 12345 98346
 

Sample Output

NO YES
 

Source
2008 “Insigma International Cup” Zhejiang Collegiate Programming Contest - Warm Up(3)
 

Recommend
lcy   |   We have carefully selected several similar problems for you:   1247  1800  1677  1298  2846 


代码如下:
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

const int maxn = 1e4+10;
struct node{
     int cnt;
     node *next[10];
};

node *root;

struct word{
      char phone[15];
      int len;
}a[maxn];

bool cmp(word p ,word q){
   return p.lennext[in]==NULL){
            q=(node *)malloc(sizeof(node));
            q->cnt=1;
            for (int k=0;k<10;k++) q->next[k]=NULL;

            p->next[in]=q;
            p=p->next[in];
        }
        else {
            p->next[in]->cnt++;
            p=p->next[in];
        }
     }
}

bool query(char *str){
    int len=strlen(str);
    node *p=root, *q;
    for (int i=0;inext[in];
        if (p==NULL) return 0;
    }
    return p->cnt;
}

void freetree(node *str){  //释放内存,不然会爆掉
    if (str==NULL) return;
    for (int i=0;i<10;i++){
        if (str->next[i]!=NULL) freetree(str->next[i]);
    }
    free(str);
    return;
}

int main(){
    std::ios::sync_with_stdio(false); //提升cin输入效率
    int t,n;
    cin >> t;
    while(t--){
        cin >> n;
        for (int i=0;i>a[i].phone;
            a[i].len=strlen(a[i].phone);
        }
        sort(a,a+n,cmp); //比较的是word类型,所以要自定义一个cmp函数

        root=(node *)malloc(sizeof(node)); //动态申请内存,所以最后要释放
        for (int i=0;i<10;i++) root->next[i]=NULL; //root不是真的字符串,所以root的cnt设置为零
        create(a[n-1].phone); //从长度最大的字符串开始插入
        bool flag=1;

        for (int i=n-2;i>=0;i--)
            if (query(a[i].phone)==0){
                 create(a[i].phone);
            }
            else{
                flag=0;
                break;
            }

        if (flag) cout<<"YES"<


你可能感兴趣的:(字典树)