数学-线性基
题目描述
XOR is a kind of bit operator, we define that as follow: for two binary base number A and B, let C=A XOR B, then for each bit of C, we can get its value by check the digit of corresponding position in A and B. And for each digit, 1 XOR 1 = 0, 1 XOR 0 = 1, 0 XOR 1 = 1, 0 XOR 0 = 0. And we simply write this operator as ^, like 3 ^ 1 = 2,4 ^ 3 = 7. XOR is an amazing operator and this is a question about XOR. We can choose several numbers and do XOR operatorion to them one by one, then we get another number. For example, if we choose 2,3 and 4, we can get 234=5. Now, you are given N numbers, and you can choose some of them(even a single number) to do XOR on them, and you can get many different numbers. Now I want you tell me which number is the K-th smallest number among them.
输入
First line of the input is a single integer T(T<=30), indicates there are T test cases.
For each test case, the first line is an integer N(1<=N<=10000), the number of numbers below. The second line contains N integers (each number is between 1 and 10^18). The third line is a number Q(1<=Q<=10000), the number of queries. The fourth line contains Q numbers(each number is between 1 and 10^18) K1,K2,......KQ.
输出
For each test case,first output Case #C: in a single line,C means the number of the test case which is from 1 to T. Then for each query, you should output a single line contains the Ki-th smallest number in them, if there are less than Ki different numbers, output -1.
样例输入 Copy
2
2
1 2
4
1 2 3 4
3
1 2 3
5
1 2 3 4 5
样例输出 Copy
Case #1:
1
2
3
-1
Case #2:
0
1
2
3
-1
设原集为S,线性基为P,若|S|>|P|,则异或会出现0。若|P|==n,则会产生2^n个不同数(包括0)
而线性基不包含0元素,故若|S|中元素可以异或出0,k需要自减
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e4+10;
ll a[N],d[64],t[64];//注意:2的六十次方大于1e18
void solve()
{
memset(d,0,sizeof d);
memset(t,0,sizeof t);
int n;
bool flag=0;//flag表示是否存在数为0
cin>>n;
for(int i=0;i<n;++i)
{
cin>>a[i];
ll x=a[i];
for(int j=61;j>=0;--j)
{
if((x>>j)&1)
{
if(!d[j]) {d[j]=x;break;}//注意:如果此处d[j]等于x需要break掉,不能继续循环
else x^=d[j];
}
}
}
for(int i=0;i<=61;++i)
{
for(int j=i+1;j<=61;++j)
{
if(d[j]>>i&1) d[j]^=d[i];
}
}
int cnt=0;
for(int i=0;i<=61;++i) if(d[i]) t[cnt++]=d[i];
if(cnt<n) flag=1;
int q;
ll k;
cin>>q;
for(int i=0;i<q;++i)
{
cin>>k;
ll ans=0;
if(flag) k--;
if(k>=(1ll<<cnt))
{
cout<<"-1"<<'\n';continue;
}
for(int j=0;j<=61;++j)
{
if(k>>j&1) ans^=t[j];
}
cout<<ans<<'\n';
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int T;
cin>>T;
for(int i=1;i<=T;++i)
{
cout<<"Case #"<<i<<':'<<'\n';
solve();
}
}
posted on
浙公网安备 33010602011771号