Educational Codeforces Round 134 D. Maximum AND

这篇博客探讨了一种通过改变数组顺序来最大化位运算结果的问题。利用贪心策略,从高位到低位逐位检查,确保在每一位上,数组元素异或操作后能够产生最多的1。通过比较数组元素与位运算后的结果,找到合适的顺序,以实现最大值。文章介绍了具体的算法实现,并提供了代码示例。
摘要由CSDN通过智能技术生成

题意:给定两个数组a,b,对ai,bi进行异或位运算获得ci构成一个数组c,先构造一个函数f(a,b)=c1&c2&⋯&cn,欲通过改变b数组顺序的方式使得得到该函数的最大值。

二进制按位来看,每一位上欲使得ci的值为一,需找到b的一个顺序使得在该位上,所有的ai与bi都不同(即一个是1一个是0),贪心的想,我们需要优先保证高位上是一,然后贪心的将尽可能大的每一位都弄成1。

可见最难的是保证前面的1仍然存在的同时贪心的让后面的位变为1,因此,我们采用这样一种方法,从大到小枚举位数,保存前一位数的答案ans(即最大值),通过两个数组p,q保存ans|1<<j(j为当前枚举的位数)分别与ai,~bi的&,分sort一下,若qi等于pi即说明该位可以选取为一,更新答案最后得到的ans即为最终答案

这样做为什么是正确的呢?首先由于最后c数组是&因此只有当所有ci当前位上为1时,ans的位上才是1,因此就必须保证ai的1与bi的0的数量是相等的,当与ans&之后,只留下了前i位,由于ans是前一位上的正确ans因此,如果qi与pi上的值相等,即可以使当前位上的值为1。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<algorithm>
#include<string>
#include<bitset>
#include<cmath>
#include<array>
#include<atomic>
#include<sstream>
#include<stack>
#include<iomanip>
//#include<bits/stdc++.h>

//#define int ll
#define pb push_back
#define endl '\n'
#define x first
#define y second
#define Endl endl
#define pre(i,a,b) for(int i=a;i<=b;i++)
#define rep(i,b,a) for(int i=b;i>=a;i--)
#define si(x) scanf("%d", &x);
#define sl(x) scanf("%lld", &x);
#define ss(x) scanf("%s", x);
#define YES {puts("YES");return;}
#define NO {puts("NO"); return;}
#define all(x) x.begin(),x.end()

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef pair<int, PII> PIII;
typedef pair<char, int> PCI;
typedef pair<int, char> PIC;
typedef pair<double, double> PDD;
typedef pair<ll, ll> PLL;
const int N = 200010, M = 2 * N, B = N, MOD = 998244353;
const int INF = 0x3f3f3f3f;
const ll LLINF = 0x3f3f3f3f3f3f3f3f;

int dx[4] = { -1,0,1,0 }, dy[4] = { 0,1,0,-1 };
int n, m, k;
int a[N], b[N];
int p[N], q[N];

ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll lowbit(ll x) { return x & -x; }
ll qmi(ll a, ll b, ll mod) {
    ll res = 1;
    while (b) {
        if (b & 1) res = res * a % mod;
        a = a * a % mod;
        b >>= 1;
    }
    return res;
}

inline void init() { }

bool check(int x)
{
    pre(i, 1, n) p[i] = a[i] & x;
    pre(i, 1, n) q[i] = ~b[i] & x;
    sort(p + 1, p + 1 + n); sort(q + 1, q + 1 + n);
    pre(i, 1, n) if (p[i] != q[i])return false;
    return true;
}

void slove()
{
    cin >> n;
    pre(i, 1, n) cin >> a[i];
    pre(i, 1, n)  cin >> b[i];

    int ans = 0;
    rep(i, 29, 0)
    {
        if (check(ans | (1 << i)))
            ans |= (1 << i);
    }
    cout << ans << endl;
}

signed main()
{
    int _;
    cin >> _;
    //_ = 1;
    init();
    while (_--)
    {
        slove();
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值