題目大意:
- 給 n 串電話號碼 , 如果有任意號碼是其他號碼的前綴,就輸出 NO ,否則輸出 YES
解題過程:
- 思路是利用trie樹(字典樹)來解決.
- 但在寫代碼的過程中,開始是每次遇到錯誤的情況就輸出並且break,這到這了我不會將所有的電話號碼都讀入,而將一部分電話號碼放到下一組數據的bug.
AC代碼:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
#define rep(i,l,p) for(int i =l;i<=p;i++)
#define fread() freopen("in.txt","r",stdin)
int T,n;
int tr[100005][11];
bool endf[100005];
int tot,nx;
char s[15];
int main(int argc, char const *argv[])
{
scanf("%d",&T);
while(T--){
memset(endf,false,sizeof(endf));
memset(tr,0,sizeof(tr));
tot = 0;
scanf("%d",&n);
bool flag = true;
rep(i,1,n){
scanf("%s",s);
nx = 0;
int len = strlen(s);
int num;
rep(j,0,len-1){
num = s[j] - '0';
if( j == len-1 && tr[nx][num] != 0){
flag = false;
}
if(tr[nx][num] == 0) tr[nx][num] = ++tot;
nx = tr[nx][num];
if(endf[nx]){
flag = false;
}
}
endf[nx] = true;
}
if(flag) printf("YES\n");
else printf("NO\n");
}
return 0;
}