4089:电话号码
总时间限制:
1000ms
内存限制:
65536kB
描述
给你一些电话号码,请判断它们是否是一致的,即是否有某个电话是另一个电话的前缀。比如:
Emergency 911
Alice 97 625 999
Bob 91 12 54 26
在这个例子中,我们不可能拨通Bob的电话,因为Emergency的电话是它的前缀,当拨打Bob的电话时会先接通Emergency,所以这些电话号码不是一致的。
输入
第一行是一个整数t,1 ≤ t ≤ 40,表示测试数据的数目。
每个测试样例的第一行是一个整数n,1 ≤ n ≤ 10000,其后n行每行是一个不超过10位的电话号码。
输出
对于每个测试数据,如果是一致的输出“YES”,如果不是输出“NO”。
样例输入
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346
样例输出
NO
YES
#include <iostream>
#include<stdio.h>
using namespace std;
//http://bailian.openjudge.cn/practice/4089/
//tire树,还需要熟悉
struct P{
bool flag;//true的话就是电话号码已结束
P* next[10];
}s;
int t,n;
char a[11];
void init(){
s.flag=false;
for(int i=0;i<10;i++){
(s.next)[i]=NULL;
}
}
bool add(int i,P* p){
//前缀和后缀都需要判断
if(p->flag==true)return false;
if(a[i]=='\0'){//先输入110,后输入11的情况
p->flag=true;
bool f=true;
for(int j=0;j<10;j++){
if((p->next)[j]!=NULL){
f=false;
}
}
return f;
}
int x=a[i]-'0';
if((p->next)[x]==NULL){
(p->next)[x]=new P;
(p->next)[x]->flag=false;
for(int j=0;j<10;j++){
(((p->next)[x])->next)[j]=NULL;
}
}
if(add(i+1,(p->next)[x]))
return true;
return false;
}
int main(int argc, char** argv) {
cin>>t;
while(t--){
init();
cin>>n;
bool f=true;
while(n--){
cin>>a;
if(!add(0,&s)){
f=false;
//break; 不能break,因为这样就没有输入完就停止了
}
}
if(f){
cout<<"YES"<<endl;
}
else cout<<"NO"<<endl;
}
return 0;
}
9.19第二次写
#include<iostream>
using namespace std;
//http://bailian.openjudge.cn/practice/4089/
//错误点:第一次竟然输入一个字符串就初始化一遍树了。
// x->next[tmp]==NULL的时候忘记new一个node了
struct node{
bool b;//叶子节点时为true
node *next[12];
};
int t,n,flag;
char a[11000][20];
node *root=new node;
bool f(node *x,int k,int e){
if(x->b==true)return false;
if(a[k][e]=='\0'){
x->b=true;
bool ff=true;
for(int i=0;i<10;i++){
if(x->next[i]!=NULL){
ff=false;
break;
}
}
return ff;
}
int tmp=a[k][e]-'0';
if(x->next[tmp]==NULL){
x->next[tmp]=new node;
x->next[tmp]->b=false;
for(int i=0;i<10;i++){
x->next[tmp]->next[i]=NULL;
}
}
//不需要写else,因为两个的操作一样都是下面的If
if(f(x->next[tmp],k,e+1)==true)return true;
return false;
}
int main(){
cin>>t;
while(t--){
cin>>n;
flag=0;
for(int i=0;i<n;i++){
cin>>a[i];
}
root->b=false;//初始化
for(int i=0;i<10;i++){
root->next[i]=NULL;
}
for(int j=0;j<n;j++){
if(f(root,j,0)==false){
cout<<"NO"<<endl;
flag=1;
break;
}
}
if(flag==0){
cout<<"YES"<<endl;
}
}
}