题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=3949
题目大意
给定
n
n
n个数以及q个询问,每个询问要求输出这
n
n
n个数的所有非空子集的异或值中第
k
k
k小的值,若不存在该值输出-1。
思路
裸的线性基,顺便放个板子。
维护线性基时一定要从低位往高位维护。
AC代码
#include<stdio.h>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<stdlib.h>
#include<string.h>
using namespace std;
typedef long long ll;
ll n,q,qu,t,a[100000],Case=0;
typedef struct L_B
{
#define NUM 30
private:
ll b[NUM+5],p[NUM+5],flag,cnt;
public:
void insert(ll now)//插入
{
for(int i=NUM;i>=0;--i)
{
if(now&(1ll<<i))
if(this->b[i])now^=this->b[i];
else
{
this->b[i]=now;return;
}
}
this->flag=1;
return;
}
ll kth(ll k)//取第k大
{
if(this->flag)--k;
if(!k)return 0;
ll ret=0;
if(k>=(1ll<<this->cnt))return -1;
for(int i=0;i<=this->cnt-1;++i)
if(k&(1ll<<i))
ret^=p[i];
return ret;
}
void clear()
{
this->cnt=0;this->flag=0;
for(ll i=0;i<64;i++)this->b[i]=0,this->p[i]=0;
}
void rebuild()//重构
{
for(int i=1;i<=NUM;i++)
if(this->b[i])
{
for(int j=0;j<i;j++)
{
if(this->b[i]&(1ll<<j))
this->b[i]^=this->b[j];
}
}
for(int i=0;i<=NUM;i++)
{
if(this->b[i])p[(this->cnt)++]=this->b[i];
}
return;
}
ll get_max(ll now)//取最大值
{
ll ret=now;
for(int i=NUM;i+1;--i)
{
if((ret^this->b[i])>ret)ret^=this->b[i];
}
return ret;
}
ll get_min()//取最小值
{
if(this->flag)
return 0;
for(int i=0;i<=NUM;i++)
{
if(this->b[i])return this->b[i];
}
return 0;
}
void merge(L_B n2)//合并线性基
{
for(int i = 0;i <= NUM;++i)
if(n2.b[i])
this->insert(n2.b[i]);
this->flag=this->flag|n2.flag;
return;
}
#undef NUM
} L_B;
L_B B;
int main()
{
scanf("%lld",&t);
while(t--)
{
Case++;
scanf("%lld",&n);B.clear();
for(ll i=1;i<=n;i++)scanf("%lld",&a[i]);
for(ll i=1;i<=n;i++)B.insert(a[i]);
printf("Case #%lld:\n",Case);
B.rebuild();
scanf("%lld",&q);
for(ll i=1;i<=q;i++)
{
scanf("%lld",&qu);
printf("%lld",B.kth(qu));
printf("\n");
}
}
return 0;
}