Intersection(線性基)

題目描述:
Bobo has two sets of integers A = {a1,a2,…,an}and B = {b1,b2,…,bn}
He says that x∈span(A) (or span(B)) if and only if there exists a subset of A (or B) whose exclusive-or sum equals to x.
Bobo would like to know the number of x where x∈span(A) and x∈span(B) hold simultaneously.
輸入描述:
The input contains zero or more test cases and is terminated by end-of-file. For each test case:
The first line contains an integer n.
The second line contains n integers a1,a2,…an
The third line contains n integers b1,b2,…,bn
*1≤n≤50

  • 0 ≤ ai, bi ≤ 2^60
  • The number of test cases does not exceed 5000.
    輸出描述:
    For each case, output an integer which denotes the result.

題意:
給出A,B兩個數組,定義x在Span(A)集合裏爲:A的一個子集的異或和爲x(可以是空集),求有多少個x即在Span(A)也在Span(B)中。
題解:
構造A,B線性基,對A中的每個基在B中訪問並存儲,更新答案
code:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll a[61],b[61];
bool insert(ll x,ll *t)
{
    for(int i=60;i>=0;i--)
    {
        if(!((1ll<<i)&x))continue;
        if(!t[i])
        {
            t[i]=x;
            return false;
        }
        else x^=t[i];
        if(!x)return true;
    }
    return true;
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        ll p;
        memset(a,0,sizeof a);
        memset(b,0,sizeof b);
        for(int i=1;i<=n;i++)
        {
            scanf("%lld",&p);
            insert(p,a);
        }
        for(int i=1;i<=n;i++)
        {
            scanf("%lld",&p);
            insert(p,b);
        }
        ll ans=1;
        for(int i=60;i>=0;i--)
        {
            if(!b[i])continue;
            if(insert(b[i],a))ans<<=1;
        }
        printf("%lld\n",ans);
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章