洛谷傳送門
Codeforces傳送門
題意翻譯
已知一個個節點的無向完全圖,第個節點的權值爲,與的邊的權值是,求該圖的MST的權值
解題分析
貪心地想, 從高位往低位考慮, 我們一定是先考慮在這一位都爲或都爲的數之間連上邊, 形成大的連通塊, 這樣能保證最後答案一定最小。
然後就有了一個類似CDQ的做法: 每次把當前位爲1的搞在一起, 爲0的搞在一起, 遞歸下去處理, 然後再考慮之間的連邊。
然後發現這麼搞之後每次塊之間都只需要連一條邊即可滿足, CDQ也只是一個空架子, 直接上樹, 枚舉左右兒子較小的子樹中的所有元素, 去另一個子樹中找到最優解就好了。
總複雜度。
代碼如下:
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <climits>
#include <vector>
#include <algorithm>
#define R register
#define IN inline
#define W while
#define gc getchar()
#define MX 205000
#define ls tree[now].son[0]
#define rs tree[now].son[1]
#define ll long long
template <class T>
IN void in(T &x)
{
x = 0; R char c = gc;
for (; !isdigit(c); c = gc);
for (; isdigit(c); c = gc)
x = (x << 1) + (x << 3) + c - 48;
}
template <class T> IN T max(T a, T b) {return a > b ? a : b;}
template <class T> IN T min(T a, T b) {return a < b ? a : b;}
int n, cnt,root;
struct Node
{
int son[2];
std::vector <int> ele;
} tree[MX * 30];
int val[MX];
ll ans;
void insert(int &now, R int val, R int dgt)
{
if (!now) now = ++cnt;
tree[now].ele.push_back(val);
if (dgt < 0) return;
int bit = (val >> dgt) & 1;
if (!bit) insert(ls, val, dgt - 1);
else insert(rs, val, dgt - 1);
}
int calc(R int now, R int val, R int dgt)
{
if (dgt < 0) return 0;
int bit = (val >> dgt) & 1;
if (tree[now].son[bit]) return calc(tree[now].son[bit], val, dgt - 1);
else return calc(tree[now].son[bit ^ 1], val, dgt - 1) + (1 << dgt);
}
void DFS(R int now, R int dgt)
{
if (dgt < 0) return;
if (ls) DFS(ls, dgt - 1);
if (rs) DFS(rs, dgt - 1);
if (ls && rs)
{
int best = INT_MAX;
if (tree[ls].ele.size() < tree[rs].ele.size())
for (R int i = tree[ls].ele.size() - 1; ~i; --i)
best = min(best, calc(rs, tree[ls].ele[i], dgt - 1));
else
for (R int i = tree[rs].ele.size() - 1; ~i; --i)
best = min(best, calc(ls, tree[rs].ele[i], dgt - 1));
ans += best + (1 << dgt);
}
}
int main(void)
{
in(n);
for (R int i = 1; i <= n; ++i)
{
in(val[i]);
insert(root, val[i], 30);
}
DFS(root, 30);
printf("%lld\n", ans);
}