Trie(字典树)

AcWing 835. Trie字符串统计

#include

using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 1e5 + 10;

int son[N][26],cnt[N],idx;
char str[N];


void insert(char str[]){
    int p =0;
    for(int i = 0;str[i];++i){
        int u = str[i] - &#39;a&#39;;
        if(!son[p][u]){
            son[p][u] = ++idx;
        }
        p = son[p][u];
    }
    cnt[p]++;
}
int query(char str[]){
    int p=0;
    for(int i = 0;str[i];++i){
        int u = str[i] - &#39;a&#39;;
        if(!son[p][u])return 0;
        p = son[p][u];
    }
    return cnt[p];
}
int main(){
    int n;cin >> n;
    while(n--){
        char ch;
        cin >> ch >> str;
        if(ch == &#39;I&#39;)insert(str);
        else printf("%d\n",query(str));
    }
    
    return 0;
}

AcWing 143. 最大异或对

#include

int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }

using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 100010, M = 3000000;
int son[M][2], idx, a[N];


void insert(int x){
    int p  =0;
    for(int i = 30;~i;--i){
        int &s = son[p][x >> i & 1];
        if(!s)s = ++idx;
        p = s;
    }
}

int query(int x){
    int p =0;
    int res = 0;
    for(int i = 30;~i;--i){
        int s = x >> i & 1;
        if(son[p][!s]){
            res += 1<<i;
            p = son[p][!s];
        }
        else p = son[p][s];
        
    }
    return res;
}
int main(){
    int n;cin >> n;
    for(int i  =0;i<n;++i){
        scanf("%d",&a[i]);
        insert(a[i]);
    }
    int ans =0;
    for(int i = 0;i<n;++i){
        ans = max(ans,query(a[i]));
    }
    
    printf("%d\n",ans);
    
    
    return 0;
}

你可能感兴趣的:(学习收藏,字符串,动态规划)