跳到正文

题解

CF1466C题解

baoziwu2约 3 分钟
原文
文章信息与版本

文章信息

发布
2023年2月22日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 3 分钟
题目
CF1466C

版本

  1. v2当前
  2. v1

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

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

fx={1x∈leaffsubtreex has only one subtreemax⁡y∈subtree(x){fy}+1otherwisef_x = \begin{cases} 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}

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

C++
#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;
}
原文
存档评论1 条抓取于