自己写了个动态的trie被tle了,悲剧
此题还能够先排序,然后用strncmp就可以判断字符串是否被后面的包含。
代码如下:
bool cmp(char *x,char *y) { return strcmp(x,y)<0; } int main() { int cases,number,x,i,j,flag; char **d=new char*[10000]; for(i=0;i<10000;++i) d[i]=new char[10]; scanf("%d",&cases); while(cases--) { scanf("%d",&number); for(i=0;i<number;++i) scanf("%s",d[i]); sort(d,d+number,cmp); flag=0; for(i=0;i<number;++i) if(strncmp(d[i],d[i+1],strlen(d[i])<strlen(d[i+1])?strlen(d[i]):strlen(d[i+1]))==0) { flag=1; break; } if(flag==0) printf("YES\n"); else printf("NO\n"); } return 0; }
trie代码如下:
/*==========================================================*\ | 静态trie \*==========================================================*/ struct my { int x, y;//x记录tree的下标,y记录出现的次数 }; struct trie { my next[15]; int cnt; } tree[100000]; struct phone { char s[15]; } p[10005]; bool cmp(phone a, phone b) { return strlen(a.s) > strlen(b.s); } int Index; void make_tree(char s[]) { int i, l = strlen(s); int now = 0; for (i = 0; i < l; ++i) { int v = s[i] - '0'; if (tree[now].next[v].x == 0) { tree[now].next[v].x = ++Index; tree[now].next[v].y = 1; now = Index; } else { tree[now].next[v].y++; now = tree[now].next[v].x; } } } bool search(char s[]) { int i, l = strlen(s); int now = 0; for (i = 0; i < l; ++i) { int v = s[i] - '0'; if (tree[now].next[v].y == 1) { return false; } else { now = tree[now].next[v].x; } } return true; } int main() { int t; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); int i, j; Index = 0; memset(tree, 0, sizeof(tree)); for (i = 0; i < n; ++i) { scanf("%s", p[i].s); make_tree(p[i].s); } for (i = 0; i < n; ++i) { if (search(p[i].s) == true) { printf("NO\n"); break; } } if (i == n) printf("YES\n"); } return 0; }