这题主要操作就是建立一棵01Trie树(其实就是一颗普通的二叉树嘛),由于最大值小于2^30,所以最大树高到30就好了,在树的分叉点上,左子树和右子树分别是两个集合(集合的size是叶节点的数量),根分别为A和B,深度(假设叶子节点的深度为1)为h,合并(连接)这两个集合的时候,需要从这两个集合选出两个异或值最小的数。
那么重点就是如何去选这两个数。一开始想的是暴力对比,将左右子树的数字每对都计算一遍异或,时间肯定爆炸了。
方法是选出size较小的那个集合(假设是左子树的集合),将集合中的每一个数按位从节点B开始往下走,从第h位开始一位一位地往下比对,如果对比到当前节点没有左节点的话,就走右节点,没有右节点就往左走,如果左右都有就看当前数字的对比位是0还是1,如果是1就往1的的那个节点走。最后走到叶节点就是当前数在该子树上异或能取得的最小值。
时间复杂度是树高(30)乘以节点数量2e5再乘以logn,大约一亿左右,两秒能过
#include<iostream> #include<cstring> #include<string> #include<cstdlib> #include<cstdio> #include<cmath> #include<vector> using namespace std; const int maxn = 2e5 + 5; int n, a; struct Trie { Trie(int H) :h(H), l(NULL), r(NULL) {} vector<int> vec; int h; Trie *l, *r; //l->1, r->0 } T(31); int min(int a, int b) { return a < b ? a : b; } long long solve(Trie *t) { if (t == NULL)return 0; long long ans = 0; Trie *tl = t->l, *tr = t->r, *temp; ans += (solve(tl) + solve(tr)); if (tl && tr) { int m = 0x5f3f3f3f; if (tl->vec.size() < tr->vec.size()) { for (vector<int>::iterator i = tl->vec.begin(); i != tl->vec.end(); i++) { int x = *i; temp = tr; for (int j = t->h - 2; ~j; j--) { if (!temp->l)temp = temp->r; else if (!temp->r) temp = temp->l; else { if (x >> j & 1) temp = temp->l; else temp = temp->r; } } m = min(m, x ^ temp->vec[0]); } } else { for (vector<int>::iterator i = tr->vec.begin(); i != tr->vec.end(); i++) { int x = *i; temp = tl; for (int j = t->h - 2; ~j; j--) { if (!temp->l)temp = temp->r; else if (!temp->r) temp = temp->l; else { if (x >> j & 1) temp = temp->l; else temp = temp->r; } } m = min(m, x ^ temp->vec[0]); } } ans += m; } return ans; } int main() { cin >> n; Trie *temp; while (n--) { temp = &T; cin >> a; for (int j = 30; ~j; j--) { if ((a >> j) & 1) { if (!temp->l)temp->l = new Trie(j); temp = temp->l; } else { if (!temp->r)temp->r = new Trie(j); temp = temp->r; } temp->vec.push_back(a); } } cout << solve(&T) << endl; }
codeforces 888G Xor-MST(01字典树)
最新推荐文章于 2022-09-06 17:54:51 发布