Phone List [trie树]

传送门

我们边插入边判断 ,

首先要判断插入的串有没有包含其它的串  , 我们边插入边看节点有没有值就可以了

其次要判断这个串有没有被包含 , 我们插入的时候看有没有新增节点就好

#include<bits/stdc++.h>
#define N 10050
using namespace std;
int ch[N*15][15],val[N*15],tot,T,n;
void Init(){
	memset(ch,0,sizeof(ch));
	memset(val,0,sizeof(val)); tot=0;
}
bool Insert(string s){
	int len = s.length(),now=0,cnt=0;
	for(int i=0;i<len;i++){
		int pos = s[i]-'0';
		if(!ch[now][pos]) ch[now][pos] = ++tot,cnt++;
		if(val[ch[now][pos]]) return false;
		now = ch[now][pos];
	} if(!cnt) return false; val[now] ++; return true;
}
int main(){
	scanf("%d",&T); while(T--){
		scanf("%d",&n); Init(); int flag=0;
		while(n--){
			string s; cin>>s;
			if(!Insert(s)){flag=1; break;}
		}
		while(flag && n--){string s; cin>>s;}
		if(!flag) printf("YES\n"); else printf("NO\n");
	} return 0;
}

猜你喜欢

转载自blog.csdn.net/sslz_fsy/article/details/85198929