題意:
若有單詞覆蓋輸出NO
否則輸出YES
字典樹裸題,判斷建立單詞時 路徑中是否存在 單詞結尾
#include<iostream> #include<stdio.h> #include<string> #include<string.h> #include<algorithm> #include<set> #include <cstdio> #include <cstring> #include <iostream> #include <math.h> #include <queue> #define ll intusing namespace std; inline ll Min(ll a,ll b){return a>b?b:a;} inline ll Max(ll a,ll b){return a>b?a:b;} #define Word_Len 1000000#define Sigma_size 11int ch[Word_Len][Sigma_size]; //Word_Len是字典樹的節點數 若都是小寫字母Sigma_size=26int Have_word[Word_Len]; //這個節點下有幾個單詞int val[Word_Len]; // 這個節點附帶的資訊,初始化為0表示這個節點不存在單詞,所以節點帶的資訊必須!=0int sz ; //當前節點數//初始化字典樹void init(){ sz = 1; memset(ch[0], 0, sizeof(ch[0])); memset(val, 0, sizeof(val));memset(Have_word, 0, sizeof(Have_word));}//初始化int idx(char c){ return c-'0';} //字串編號bool Creat(char *s){bool Have_creat=false; //是否建立了int u = 0, len = strlen(s);for(int i = 0; i < len; i++){int c = idx(s[i]);if(!ch[u][c]){ //節點不存在memset(ch[sz], 0, sizeof(ch[sz]));ch[u][c] = sz++;Have_creat = true;}if(Have_word[u]==1)return false;u = ch[u][c];}if(Have_word[u]==1)return false;Have_word[u]=1;return Have_creat;}char S[15];int n;int main(){int T;scanf("%d",&T);while(T--){init();int n;scanf("%d",&n);bool su=true;while(n--){scanf("%s",S);if(su)su = Creat(S);}if(su)printf("YES\n");else printf("NO\n");}return 0;}/*99211221212123412343123456812365486421344431456212354699152222323666ans:nnnyn*//*#include<iostream>#include<stdio.h>#include<string.h>#include<string>#include<algorithm>using namespace std;char s[100010][11];struct node{ int cnt; struct node *next[11]; void init(){memset(next,0,sizeof(next));}};node a[1000000];struct node *root;int indexx=0;struct node *build(){ a[indexx].cnt=1; a[indexx].init(); return &a[indexx++];}void save(char *s){ int len=strlen(s); struct node *p; p=root; for(int i=0;i<len;i++) { if(p->next[s[i]-'0']!=NULL)p->next[s[i]-'0']->cnt++; else p->next[s[i]-'0']=build(); p=p->next[s[i]-'0']; }}int search(char *s){ int len=strlen(s); struct node *p; p=root; for(int i=0;i<len;i++) { if(p->next[s[i]-'0']->cnt==1)return 1; p=p->next[s[i]-'0']; } return 0;}char str[40000][11];int main(){ int i,j,k,m,n,T; scanf("%d",&T); while(T--) { scanf("%d",&n); indexx=0; root=build(); for(i=0;i<n;i++) { scanf("%s",str[i]); save(str[i]); } int flag=1; for(i=0;i<n;i++)if(search(str[i])==0) { flag=0; break; } if(flag)puts("YES"); else puts("NO"); } return 0;}*/