牛客网 XOR【线性基】

题目链接:https://ac.nowcoder.com/acm/contest/881/H

题意:给你一个集合,问你所有异或和为0的子集的大小。

思路: 首先我们可以组成一个基底大小为r,那么剩下n-r个数就在非基底,对这n-r个元素来说,其任意一个都能够与其余n-r-1个元素构成一个数,然后再和基底异或为0,贡献是2^(n - r - 1), 那么总共就是(n - r) * 2 ^ (n - r - 1) 。

然后我们考虑基底中的数,对于其中某个数x来说,我们可以用n-r个元素构成一个新的基底,然后用其他r-1个元素加入基底,然后判断x能否插入该基底,不能的话说明可以和基底异或为0,贡献的话还是2^(n - r - 1), 因为新的基底和原来的基底秩相同。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 65;
const int maxn = 1e5 + 10;
const int mod = 1e9 + 7;
ll a[maxn], b[maxn];
ll p[N], q[N], h[N];
vector<int> pos;

ll qpow(ll a, ll b)
{
    ll res = 1;
    a = a % mod;
    while(b)
    {
        if(b & 1)
            res = res * a % mod;
        b >>= 1;
        a = a * a % mod;
    }
    return res;
}
bool ins(ll x, ll *p)
{
    for(int i = 61; i >= 0; --i)
    {
        if(x & (1ll << i))
        {
            if(!p[i])
            {
                p[i] = x;
                return true;
            }
            else
                x ^= p[i];
        }
    }
    return false;
}
bool check(ll x, ll *p) //检查能否插入
{
    for(int i = 61; i >= 0; --i)
        if(x & (1ll << i))
            x ^= p[i];
    return x == 0; //为0表示不能插入返回true
}
void init()
{
    pos.clear();
    memset(p, 0, sizeof(p));
    memset(q, 0, sizeof(q));
}

int main()
{
    int n;
    while(~scanf("%d", &n))
    {
        init();
        ll tot = 0;
        for(int i = 1; i <= n; ++i)
        {
            scanf("%lld", &a[i]);
            if(ins(a[i], p)) //能插入就插入,记录下标
                pos.push_back(i);
            else
                b[++tot] = a[i];
        }
        if(tot == 0) //基底无法异或成0
        {
            printf("0\n");
            continue;
        }
        ll ans = tot * qpow(2, tot - 1) % mod;
        for(int i = 1; i <= tot; ++i)
            ins(b[i], q);
        for(auto i : pos)
        {
            memcpy(h, q, 62 * sizeof(ll));
            for(auto j : pos) //将除了当前枚举数都加入
                if(i != j)
                    ins(a[j], h);
            if(check(a[i], h))
                ans = (ans + qpow(2, tot - 1)) % mod;
        }
        printf("%lld\n", ans);
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值