CF1466C题解

· · 题解

看到最小异或值可以想到 trie 树,但是删除操作实现过于困难,正难则反,考虑求最大保留数。

设 f_x 为在 trie 树 上以 x 为根的合法子树可以保留的最大数量,转移方程如下。

1 & x\in leaf \\ f_{subtree} & \text{x has only one subtree}\\ \max\limits_{y \in subtree(x)}\{f_y\} + 1 & \text{otherwise} \end{cases}

当 x 只有一颗子树时,答案显然为 f_{subtree},当 x 兼具左右子树时,保留一棵较大的子树,将另一棵子树的节点删到只剩一个,因为保留的子树答案是合法的,而另一颗子树上会且仅会产生一条边,所以新的答案也是合法的,即满足 x 子树内只存在一对满足题目要求的 (i,j)。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

int const N = 3e7 + 5;

inline int read() {
    int res = 0, f = 1; char c = getchar();
    while(!isdigit(c)) {
        if(c == '-') f = -1;
        c = getchar();
    }
    while(isdigit(c)) {
        res = res * 10 + c - '0';
        c = getchar();
    }
    return res * f;
}

class Tire {
    int ch[N][2], tot;
public:
    inline void insert(int const &val) {
        int p = 0;
        for(int i = 30; ~i; -- i) {
            bool x = (val >> i) & 1;
            if(!ch[p][x]) ch[p][x] = ++ tot;
            p = ch[p][x];
        }
    }

    int dfs(int x) {
        if(!ch[x][0] and !ch[x][1]) return 1;
        if(!ch[x][0]) return dfs(ch[x][1]);
        if(!ch[x][1]) return dfs(ch[x][0]);
        return max(dfs(ch[x][0]), dfs(ch[x][1])) + 1;
    }
}t;

int main() {
    int n = read();

    for(int i = 1; i <= n; ++ i)
        t.insert(read());

    printf("%d\n", n - t.dfs(0));
    return 0;
}