Codeforces Round #673 (Div. 1) C. XOR Inverse 逆序对+二进制枚举

https://codeforces.com/contest/1416/problem/C

  • 给你一个数组 a [ i ] ≥ 0 a[i]\geq0 a[i]0,让你找一个非负整数 x x x,使得让 b [ i ] = a [ i ] ⊕ x b[i]=a[i]\oplus x b[i]=a[i]x所得到的数组 b b b的逆序数 ( t h e   n u m b e r   o f   i n v e r s i o n s ) (the\ number\ of\ inversions) (the number of inversions)最少,求最小的 x x x
  • 异或问题看来一般都要按照每一位来考虑,我们从最高位往最低位考虑,什么时候能够使得数组的逆序数最少,因为最高位起到决定性的作用,如果说最高位对 1 1 1取异或所得到的逆序数小于最高位对 0 0 0取异或得到的逆序数,那么显然应该让 x x x的这一位为 1 1 1而不能是 0 0 0;如果二者相等,考虑到需要求一个最小的 x x x,这个时候 x x x的这一位就应该是 0 0 0
  • 按照这个思路我们应该能够想到思路,枚举 x x x的每一位,按照上述思路对 x x x的每一位进行赋值,最后得到的 x x x就是最小的,然后我们再计算出整个数组的逆序对即可
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int N = 3e5;
int n;
struct st{
  int id;
  int val;
  bool operator < (const st &B)const{
    return val < B.val;
  }
}s[N + 100];
int a[N + 100];
ll tree[N + 100];
int lowbit(int x){
  return x & -x;
}
void ADD(int x, int d){
  while(x <= n){
    tree[x] += d;
    x += lowbit(x);
  }
}
ll query(int x){
  ll ans = 0;
  while(x > 0){
    ans += tree[x];
    x -= lowbit(x);
  }
  return ans;
}
int main(){
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for(int i=1;i<=n;i++){
    cin >> a[i];
    s[i].id = i;
    s[i].val = a[i];
  }stable_sort(s + 1, s + 1 + n);
  ll now = 0;
  for(int i=1;i<=n;i++){
    ADD(s[i].id, 1);
    now += i - query(s[i].id);
  }
  int x = 0;
  for(int i=0;i<=30;i++){
    ll res = 0;
    for(int j=1;j<=n;j++){
      s[j].id = j;
      s[j].val = (a[j] ^ (1 << i));
    }stable_sort(s + 1, s + 1 + n);
    memset(tree, 0, sizeof tree);
    for(int j=1;j<=n;j++){
      ADD(s[j].id, 1);
      res += j - query(s[j].id);
    }
    if(res < now){
      x |= (1 << i);
    }
  }
  ll res = 0;
  memset(tree, 0, sizeof tree);
  for(int i=1;i<=n;i++){
    s[i].id = i;
    s[i].val = (x ^ a[i]);
  }stable_sort(s + 1, s + 1 + n);
  for(int i=1;i<=n;i++){
    ADD(s[i].id, 1);
    res += i - query(s[i].id);
  }
  cout << res << ' ' << x;
  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Clarence Liu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值