HDU 1671-Phone List(字典树-前缀匹配)

来源:互联网 发布:暴风王座坐骑进阶数据 编辑:程序博客网 时间:2024/04/29 06:04

Phone List

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


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
2391197625999911254265113123401234401234598346
 

Sample Output
NOYES
 

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

题目意思:

输入几组号码,对于每一组号码而言,每一个号码都不能是其它号码的前缀。
如果存在某个号码是其它号码的前缀,输出“NO”,反之输出“YES”。

解题思路:

输入时一边用一个字符串数组存储所有输入的字符串,一边插入字典树。

全部输入完毕之后,遍历之前所有输入的字符串,判断是否是某个号码的前缀。

这里注意因为肯定会和自身一次有匹配成功,所以匹配数大于1时才是和别的字符串匹配成功,即等于1时输出YES,大于1时输出NO。


/** Copyright (c) 2016, 烟台大学计算机与控制工程学院* All rights reserved.* 文件名称:tree.cpp* 作    者:单昕昕* 完成日期:2016年5月4日* 版 本 号:v1.0*/#include <cstdio>#include <cstdlib>#include <cstring>#include <iostream>using namespace std;struct Node{    int num,next[11];//num是树的数目,next指向子树};Node a[100000];int e;//e是当前树序号string ss[100000];//存储所有输入的字符串void Insert(char str[]){    int i,p=1;    for (i=0; str[i]; i++)    {        if (a[p].next[str[i]-'0']==0)//如果当前字母没有出现过        {            a[p].next[str[i]-'0']=++e;            a[e].num=0;        }        p=a[p].next[str[i]-'0'];        a[p].num++;    }}int Search(string str)//遍历输出{    int i,p=1;    for (i=0; str[i]; i++)    {        if (a[p].next[str[i]-'0']) p=a[p].next[str[i]-'0'];//如果存在当前字符串        else return 0;//不存在直接判0    }    return a[p].num;}int main (){    int t;    cin>>t;    while(t--)    {        e=1;        memset(a,0,sizeof(Node)*100000);//清空初始化        int n,i;        cin>>n;        getchar();//因为下面用gets所以这里要加一句        char str[20];        for(i=0; i<n; ++i)        {            gets(str);            ss[i]=str;//把读入的所有字符串都保存到ss中            Insert (str);//插入到字典树中        }        int flag;//是否重复的标记        for(i=0; i<n; ++i)        {            string temp=ss[i];//读取存入的字符串            if(Search(temp)!=1)//因为肯定会和自身一次有匹配成功,所以大于1时是和别的字符串匹配成功            {                flag=1;                break;            }            else flag=0;        }        if(flag) cout<<"NO"<<endl;        else  cout<<"YES"<<endl;    }    return 0;}


0 0