跳到正文

个人记录

线性基小计

Bryan1676约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年8月17日
收录
2026年11月3日
更新
2026年11月7日
篇幅
约 3 分钟

版本

  1. v1当前

线性基小计

定义

就是在一个集合 AA 中选择一些数,要求任意一个数不能被其它数表示出来,并要求他们能用异或表示出集合中的所有数

构造方法

对于每个数,考虑如何插入,从高位到低位遍历,如果这位没有数,直接插入,否则异或上这位的数然后继续向下找,正确性显然

C++
int insert(int x){
  for(int i=31;i>=0;i--){
    if((x>>i)&1){
      if(!d[i]){
        d[i]=x;
        return 1;
      }
      else x^=d[i];
    }
  }
  return 0;
}

例题

T1 [CQOI2013] 新Nim游戏

利用 NIM 游戏的经典结论,如果所有堆中石子的数量异或和不为 0,则先手必胜

目标转化为了找到一组和最大的任取一些数异或和不为 0 的使得 aa 最大的数

考虑从大到小插入线性基,如果能插入就插入,这样一定是最优的

INFO

关于为何要从大到小排序,感性理解下就是对于一个线性基里的位置,如果既可以被小数占据,又可以被大数占据,按照我们的选法一定会被大数占据,这一定是不劣的

code
C++
#include<bits/stdc++.h>
using namespace std;

#define int long long
#define PII pair<int,int>
#define fi first
#define se second
#define mk make_pair
#define pb push_back
#define ivoid inline void
ivoid wsp(int x){
	cout<<x<<" ";
}
ivoid wln(int x){
	cout<<x<<"\n";
}
ivoid wstr(string s){
	cout<<s<<"\n";
}
#define cout cerr

const int maxn=1e2+10;
int n,a[maxn];

struct LinearBase{
	int d[maxn];
	int insert(int x){
		for(int i=31;i>=0;i--){
			if((x>>i)&1){
				if(!d[i]){
					d[i]=x;
					return 1;
				}
				else x^=d[i];
			}
		}
		return 0;
	}
}lb;

signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	cin>>n;
	for(int i=1;i<=n;i++) cin>>a[i];
	sort(a+1,a+n+1,greater<int>());
	int ans=0;
	for(int i=1;i<=n;i++){
		if(!lb.insert(a[i])) ans+=a[i];
	} 
	wln(ans);
	return 0;
}
原文