题意:给一组串,是否存在一个串是另一个的前缀。
分析:val[N]保存树节点上是否组成一个串
#include <map> #include <set> #include <list> #include <cmath> #include <queue> #include <stack> #include <cstdio> #include <vector> #include <string> #include <cctype> #include <complex> #include <cassert> #include <utility> #include <cstring> #include <cstdlib> #include <iostream> #include <algorithm> using namespace std; typedef pair<int,int> PII; typedef long long ll; #define lson l,m,rt<<1 #define pi acos(-1.0) #define rson m+1,r,rt<<11 #define All 1,N,1 #define read freopen("in.txt", "r", stdin) #define N 100010 const ll INFll = 0x3f3f3f3f3f3f3f3fLL; const int INF= 0x7ffffff; const int mod = 1000000007; struct Trie{ int ch[N][20]; int val[N],num; void init(){ num=1; memset(ch[0],0,sizeof(ch[0])); } int idx(char c){return c-‘0‘;} int build(char *s){ int u=0,len=strlen(s),f=0; for(int i=0;i<len;++i){ int v=idx(s[i]); if(!ch[u][v]){ memset(ch[num],0,sizeof(ch[num])); val[num]=0; ch[u][v]=num++; f=1; } u=ch[u][v]; if(val[u]==1)return 0; } if(val[u]==1)return 0; val[u]=1; if(!f)return 0; return 1; } }trie; int main() { int t,n; char str[20]; scanf("%d",&t); while(t--){ trie.init(); scanf("%d",&n); int f=1; for(int i=0;i<n;++i){ scanf("%s",str); if(f){ f=trie.build(str); } } if(f)printf("YES\n"); else printf("NO\n"); } return 0; }
时间: 2024-11-15 00:55:03