1. 程式人生 > >【POJ3630】Phone List(字典樹)

【POJ3630】Phone List(字典樹)

problem

  • 給定n個長度不超過10的數字串(n<10^4)
  • 問其中是否存在兩個陣列串a,b,滿足a是b的字首。存在輸出NO,不存在輸出YES

solution

  • 將所有數字串構建成字典樹
  • 在插入過程中,如果沒有新建任何節點(當前串是之前串的字首))或者插入過程中經過某個帶結尾標記的串(之前串是當前串的字首),則存在字首情況。

codes

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 1e5
+10; int tire[maxn][26], val[maxn], tot; void build(){ tot = 1; memset(tire,0,sizeof(tire)); memset(val,0,sizeof(val)); } bool insert(char *s){ bool jingguo = false, xinjian = false; int len = strlen(s), u = 1; for(int i = 0; i < len; i++){ int c = s[i]-'0'; if
(tire[u][c]==0){ tire[u][c] = ++tot; xinjian = true; } u = tire[u][c]; if(val[u])jingguo = true; } val[u] = 1; if(!xinjian || jingguo)return true; return false; } char s[20]; int main(){ int T; scanf("%d",&T); while(T--){ int
n; scanf("%d",&n); build(); bool ans = false; for(int i = 1; i <= n; i++){ scanf("%s",s); if(insert(s))ans = true;//存在字首 } if(ans)cout<<"NO\n"; else cout<<"YES\n"; } return 0; }