经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C » 查看文章
cf888G. Xor-MST(Boruvka最小生成树 Trie树)
来源:cnblogs  作者:自为风月马前卒  时间:2018/10/15 9:26:56  对本文有异议

题意

题目链接

给出\(n\)点,每个点有一个点权\(a[i]\),相邻两点之间的边权为\(a[i] \oplus a[j]\),求最小生成树的值

Sol

非常interesting的一道题,我做过两种这类题目,一种是直接打表找规律,另一种就像这种用Boruvka算法加一些骚操作来搞。

首先,把所有元素扔到Trie树里面,这样对于Trie树上的每一层(对应元素中的每一位)共有两种情况:

  1. 全为0或全为1

  2. 一部分为0另一部分为1

对于第一种情况,我们无需考虑,因为任意点相邻产生的贡献都是0,对于第二种情况,需要找到一条最小的边来连接链各个集合,这可以在Trie树上贪心实现

另外还有一个小Trick,我们把元素从小到大排序,这样Trie树上每个节点对应的区间就都是连续的

实现的时候可以从底往上update,也可以从上往下dfs

时间复杂度:\(O(nlognlog_{max(a_i)})\)

本来以为这题要写一年,结果写+调只用了1h不到?

  1. #include<bits/stdc++.h>
  2. #define Pair pair<int, int>
  3. #define fi first
  4. #define se second
  5. #define MP(x, y) make_pair(x, y)
  6. #define LL long long
  7. using namespace std;
  8. const int MAXN = 2e5 + 10, B = 31, INF = 1e9 + 7;
  9. inline LL read() {
  10. char c = getchar(); LL x = 0, f = 1;
  11. while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
  12. while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
  13. return x * f;
  14. }
  15. int N, a[MAXN], L[MAXN * 30], R[MAXN * 30], ch[MAXN * 30][2], tot = 0;
  16. void insert(int val, int pos) {
  17. int now = 0;
  18. for(int i = B; ~i; i--) {
  19. int x = val >> i & 1;
  20. if(!ch[now][x]) ch[now][x] = ++tot, L[tot] = pos, R[tot] = pos;//?????????????λ
  21. L[now] = min(L[now], pos); R[now] = max(R[now], pos);
  22. now = ch[now][x];
  23. }
  24. }
  25. int Query(int val, int now, int NowBit) {
  26. LL ans = 1 << (NowBit + 1);
  27. for(int i = NowBit; ~i; i--) {
  28. int x = val >> i & 1;
  29. if(ch[now][x]) now = ch[now][x];
  30. else ans |= 1 << i, now = ch[now][x ^ 1];
  31. }
  32. return ans;
  33. }
  34. LL dfs(int x, int NowBit) {
  35. LL res = 0;
  36. if(NowBit == 0)
  37. return (ch[x][0] && ch[x][1]) ? (a[L[ch[x][0]]] ^ a[R[ch[x][1]]]) : 0;
  38. //if(NowBit == 0) return ;
  39. if(ch[x][0] && ch[x][1]) {
  40. int tmp = INF;
  41. for(int i = L[ch[x][0]]; i <= R[ch[x][0]]; i++) tmp = min(tmp, Query(a[i], ch[x][1], NowBit - 1));
  42. res += tmp;
  43. }
  44. if(ch[x][0]) res += dfs(ch[x][0], NowBit - 1);
  45. if(ch[x][1]) res += dfs(ch[x][1], NowBit - 1);
  46. return res;
  47. }
  48. int main() {
  49. N = read();
  50. for(int i = 1; i <= N; i++) a[i] = read();
  51. sort(a + 1, a + N + 1);
  52. L[0] = INF; R[0] = 0;
  53. for(int i = 1; i <= N; i++) insert(a[i], i);
  54. cout << dfs(0, B);
  55. return 0;
  56. }
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号