码迷,mamicode.com
首页 > 其他好文 > 详细

Phone List

时间:2018-05-27 16:24:59      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:mem   medium   dig   ble   没有   term   enc   string   ret   

描述

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:

  • Emergency 911
  • Alice 97 625 999
  • 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.

输入

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.

输出

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

样例输入

2
3
911
97625999
91125426
5
113
12340
123440
12345
98346

样例输出

NO
YES

解题思路:考虑一个字符串是不是其它字符串的前缀, 或者其它的字符串是它的前缀, 开始没有考虑到是不是其它子串的情况。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct node
{
    node *next[10];
    bool is;
    node()
    {
        is=false;
        memset(next,NULL,sizeof(next));
    }
};
int insert(node *root,char s[])
{
    int i=0;
    int flag=1;
    node *p=root;
    while(s[i])
    {
        int j=s[i++]-0;
        if(p->next[j]==NULL)
        {
            p->next[j]=new node();
            flag=0;
        }
        p=p->next[j];
        if(p->is==true) return 0;
    }
    p->is=true;
    if(flag==1) return 0;
    return 1;
}
int main()
{
    int t,n,m,i,j,k;
    cin>>n;
    while(n--)
    {
        node *root=new node();
        cin>>m;
        int flag=1;
        for(i=0;i<m;i++)
        {
            char s[11];
            scanf("%s",s);
            if(flag)
            {
                int g=insert(root,s);
                if(g==0) flag=0;
            }
        }
        if(flag) cout<<"YES\n";
        else cout<<"NO\n";
    }
}

 

Phone List

标签:mem   medium   dig   ble   没有   term   enc   string   ret   

原文地址:https://www.cnblogs.com/ww123/p/9096250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!