標籤:trie樹
題意:給你n個字串 如果存在某個字串是另一個字串的首碼 輸出NO否則輸出YES
思路:和poj2001很像 代碼稍微改改就行, 字典樹 如果一個字串不存在特有首碼,則說明是NO的情況 如果所有字串都有特有首碼 則是YES的情況
注意: 每次注意釋放記憶體 不然會逾時
代碼:
#include <algorithm>#include <iostream>#include <sstream>#include <cstdlib>#include <cstring>#include <iomanip>#include <cstdio>#include <string>#include <bitset>#include <vector>#include <queue>#include <stack>#include <cmath>#include <list>#include <map>#include <set>#define sss(a,b,c) scanf("%d%d%d",&a,&b,&c)#define mem1(a) memset(a,-1,sizeof(a))#define mem(a) memset(a,0,sizeof(a))#define ss(a,b) scanf("%d%d",&a,&b)#define s(a) scanf("%d",&a)#define p(a) printf("%d\n", a)#define INF 0x3f3f3f3f#define w(a) while(a)#define PI acos(-1.0)#define LL long long#define eps 10E-9#define N 100000#define mod 100000000using namespace std;void mys(int& res){ int flag=0; char ch; while(!(((ch=getchar())>='0'&&ch<='9')||ch=='-')) if(ch==EOF) res=INF; if(ch=='-') flag=1; else if(ch>='0'&&ch<='9') res=ch-'0'; while((ch=getchar())>='0'&&ch<='9') res=res*10+ch-'0'; res=flag?-res:res;}void myp(int a){ if(a>9) myp(a/10); putchar(a%10+'0');}/*************************THE END OF TEMPLATE************************/char str[10011][15];struct node{ int sum; struct node *next[10]; node ()//建構函式 初始化用 { sum=0; mem(next); }} ;node *root = NULL;void maketree(char *s){ node *p=root; node *tmp=NULL; for(int i=0; i<strlen(s); i++) { if(p->next[s[i]-'0']==0) { tmp=new node ; p->next[s[i]-'0']=tmp; } p=p->next[s[i]-'0']; p->sum++; }}int searchtree(char *s){ node *p=root; int cnt = 0; for(int i=0; i<strlen(s); i++) { p=p->next[s[i]-'0']; if(p->sum==1) break; cnt ++; } // cout<<s<< ":"<<cnt<<endl; return cnt;}void del(node *rt){ for(int i=0;i<10;i++){ if(rt->next[i]!=NULL){ del(rt->next[i]); } } free(rt);}int main(){ int n, t; s(t); w(t--){ root = new node; s(n); for(int i=0; i<n; i++){ cin>>str[i]; maketree(str[i]); } bool flag = false; for(int i=0; i<n; i++){ if(strlen(str[i]) == searchtree(str[i])){ flag = true; break; } } if(flag) cout<<"NO"<<endl; else cout<<"YES"<<endl; del(root); } return 0;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
hdu1671 trie樹