CodeForces 888G :Xor-MST 异或最小生成树

传送门

题意

给定一个 n n n个节点的完全图,每个节点有个编号 a i a_i ai,节点 i i i和节点 j j j之间边的权值为 a i ⊕ a j a_i \oplus a_j aiaj,求该图的最小生成树的权值和。

分析

首先放上我CoolGuang的题解,讲的比较详细
我个人的理解是,如果我们去递归整个字典树,如果遇到一个点即有左子树又有右子树,那么我们把右子树的所有点看成已经匹配好的一个团,左子树内的所有点看成匹配好的一个团,那么左右子树两个团直接需要进行匹配连接,那么我们去遍历左子树内的每一个点,查询在右子树的字典树上的最小异或值,然后左右子树继续往下递归即可

代码

#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef vector<int> VI;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int N = 1e7 + 10;
const ll mod = 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a) {
    char c = getchar(); T x = 0, f = 1; while (!isdigit(c)) {if (c == '-')f = -1; c = getchar();}
    while (isdigit(c)) {x = (x << 1) + (x << 3) + c - '0'; c = getchar();} a = f * x;
}
int gcd(int a, int b) {return (b > 0) ? gcd(b, a % b) : a;}
int tr[N][2],idx;
int L[N],R[N];
ll a[N];
int n;

void insert(ll x,int q){
    int p = 0;
    for(int i = 32;~i;i--){
        int t = (x >> i) & 1;
        if(!tr[p][t]) tr[p][t] = ++idx;
        p = tr[p][t];
        if(!L[p]) L[p] = q;
        R[p] = q;
    }
}

ll query(int p,int dep,ll x){
    ll ans = 0; 
    for(int i = dep;~i;i--){
        int q = (x >> i & 1);
        if(tr[p][q]) p = tr[p][q];
        else{
            p = tr[p][!q];
            ans += (1ll << i);
        }
    }
    return ans;
}

ll dfs(int p,int dep){
    if(tr[p][1] && tr[p][0]){
        int x = tr[p][0],y = tr[p][1];
        ll mi = INF;
        for(int i = L[x];i <= R[x];i++) mi = min(query(y,dep - 1,a[i]) + (1ll << dep),mi);
        return mi + dfs(tr[p][0],dep - 1) + dfs(tr[p][1],dep - 1);
    }
    else if(tr[p][1]) return dfs(tr[p][1],dep - 1);
    else if(tr[p][0]) return dfs(tr[p][0],dep - 1);
    return 0;
}

int main() {
    read(n);
    for(int i = 1;i <= n;i++) read(a[i]);
    sort(a + 1,a + 1 + n);
    for(int i = 1;i <= n;i++) insert(a[i],i);
    dl(dfs(0,32));
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值